gpt4 book ai didi

java - Google Guava "zip"两个列表

转载 作者:IT老高 更新时间:2023-10-28 21:04:14 28 4
gpt4 key购买 nike

使用 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());

关于java - Google Guava "zip"两个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19040802/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com