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

后端 未结 5 1454
攒了一身酷
攒了一身酷 2020-12-06 02:48

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

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-06 03:22

    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  List> zip(List... lists) {
        List> zipped = new ArrayList>();
        for (List list : lists) {
            for (int i = 0, listSize = list.size(); i < listSize; i++) {
                List list2;
                if (i >= zipped.size())
                    zipped.add(list2 = new ArrayList());
                else
                    list2 = zipped.get(i);
                list2.add(list.get(i));
            }
        }
        return zipped;
    }
    
    public static void main(String[] args) {
            List x = Arrays.asList(1, 2, 3);
            List y = Arrays.asList(4, 5, 6);
            List> zipped = zip(x, y);
            System.out.println(zipped);
    }
    

    Prints

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

提交回复
热议问题