Google Guava“压缩”两个列表

使用Google Guava(Google Commons),是否可以将两个大小相等的列表合并为一个列表,而新列表包含两个输入列表的复合对象?

例:

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 + ")";

}

}

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);

将输出:

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

回答:

从Guava

21开始,可以通过以下方式实现Streams.zip()

List<Person> persons = Streams.zip(names.stream(), ages.stream(), Person::new)

.collect(Collectors.toList());

以上是 Google Guava“压缩”两个列表 的全部内容, 来源链接: utcz.com/qa/403853.html

回到顶部