Google Guava “zip” two lists

前端 未结 6 2028
萌比男神i
萌比男神i 2020-12-03 13:34

Using Google Guava (Google Commons), is there a way to merge two equally sized lists into one list, with the new list containing composite objects of the two input lists?

6条回答
  •  感动是毒
    2020-12-03 14:10

    Here's a generic way to zip lists with vanilla Java. Lacking tuples, I opted to use a list of map entries (If you don't like to use map entries, introduce an additional class ZipEntry or something).

    public static  List> zip(List zipLeft, List zipRight) {
        List> zipped = new ArrayList<>();
        for (int i = 0; i < zipLeft.size(); i++) {
            zipped.add(new AbstractMap.SimpleEntry<>(zipLeft.get(i), zipRight.get(i)));
        }
        return zipped;
    }
    

    To support arrays as well:

    @SuppressWarnings("unchecked")
    public static  Map.Entry[] zip(T1[] zipLeft, T2[] zipRight) {
        return zip(asList(zipLeft), asList(zipRight)).toArray(new Map.Entry[] {});
    }
    

    To make it more robust add precondition checks on list sizes etc, or introduce left join / right join semantics similar to SQL queries.

提交回复
热议问题