Steve Kuo Steve Kuo - 5 months ago 102
Java Question

Google Guava "zip" two lists

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?

Example:

public class Person {
public final String name;
public final int age;

public Person(String name, int age) {
this.name = name;
this.age = age;
}

public String toString() {
return "(" + name + ", " + age + ")";
}
}


and

List<String> names = Lists.newArrayList("Alice", "Bob", "Charles");
List<Integer> ages = Lists.newArrayList(42, 27, 31);

List<Person> persons =
transform with a function that converts (String, Integer) to Person
System.out.println(persons);


Would output:

[(Alice, 42), (Bob, 27), (Charles, 31)]

Answer

Looks like this is not currently in Guava, but is a desired feature. See this guava-libraries discussion this github issue, in particular Iterators.zip().