Albert Albert - 1 month ago 5
Java Question

Java: How to write a `zip` function? What should be the return type?

What should be the return type of a

zip
function? (
zip
as in most other languages, e.g. read here)

I thought about some Pair-type but that does not exist in Java. It is often states that this is because a specialized Pair-class is better than a general one (see this question). However, this is not possible in a general
zip
function.

Answer

Since you appear to be determined to ignore people with many years Java experience, here is code which does the same as the zip function in python.

public static <T> List<List<T>> zip(List<T>... lists) {
    List<List<T>> zipped = new ArrayList<List<T>>();
    for (List<T> list : lists) {
        for (int i = 0, listSize = list.size(); i < listSize; i++) {
            List<T> list2;
            if (i >= zipped.size())
                zipped.add(list2 = new ArrayList<T>());
            else
                list2 = zipped.get(i);
            list2.add(list.get(i));
        }
    }
    return zipped;
}

public static void main(String[] args) {
        List<Integer> x = Arrays.asList(1, 2, 3);
        List<Integer> y = Arrays.asList(4, 5, 6);
        List<List<Integer>> zipped = zip(x, y);
        System.out.println(zipped);
}

Prints

[[1, 4], [2, 5], [3, 6]]
Comments