Google Guava “zip” two lists

前端 未结 6 2029
萌比男神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:07

    Here's a version with no explicit iteration, but it's getting pretty ugly.

    List persons = ImmutableList.copyOf(Iterables.transform(
        ContiguousSet.create(Range.closedOpen(0, names.size()),
            DiscreteDomain.integers()),
        new Function() {
          @Override
          public Person(Integer index) {
            return new Person(names.get(index), ages.get(index));
          }
        }));
    

    It's really not much better than having explicit iteration, and you probably want some level of bounds checking to ensure that the two inputs are indeed of the same size.

提交回复
热议问题