我使用 java 8,我有两个对象:
人类:
public class Person {
private String id;
private String name;
public Person() {
}
public Person(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
'}';
}
}
Person1 类:
public class Person1 {
private String id;
private String name;
public Person1() {
}
public Person1(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person1{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
'}';
}
}
我有两个列表:
List<Person> persons= Arrays.asList(new Person("1","A"),new Person("2","B"));
List<Person1> persons1 = Arrays.asList(new Person1("3","C"),new Person1("1","F"));
现在我想使用流 java 8 循环两个列表并进行比较。如果列表 persons 中的任何对象等于 persons1 ,我将创建新列表并为其设置新值。示例:如果 Person1("1","F") 等于 Person("1","A") 因为我使用 id 比较它,我从 Person1 得到名字设置为人。结果:Person("1,"F") 并添加两个新列表。
我使用时的代码:
for (Person person : persons) {
for (Person1 person1 : persons1 ) {
if (person1.getId().equals(person.getId())) {
person.setName(person1.getId());
break;
}
}
}
现在我想将其转换为 Stream,新列表如下所示:
List<Person> personList =
list.stream()
.filter (
person -> list1.stream()
.anyMatch(person1 -> person1.getId()== person.getId()))
.collect(Collectors.toList());
但它只过滤人。我想比较两个列表对象。如果相同的 id,我想将 persons1 中对象的名称设置为 persons。我知道我们可以在流 java 8 中使用 map ,但我不知道该怎么做。请帮忙
最佳答案
有些任务最好用流来完成,而另一些则用迭代来完成。许多任务最好通过结合这两种方法来完成。在此解决方案中,使用流来构建 map ,然后使用迭代来更新匹配人员的姓名。您的解决方案以二次时间运行,而此解决方案以线性时间复杂度运行。
Map<String, String> idToNameMap = persons1.stream()
.collect(Collectors.toMap(Person1::getId, Person1::getName, (a, b) -> a));
for (Person person : persons) {
if (idToNameMap.containsKey(person.getId())) {
person.setName(idToNameMap.get(person.getId()));
}
}
关于java - 如何在 java 8 中使用流过滤两个列表对象并将值设置为新列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56993242/