我有 2 个类(class)列表:
List<Person> ls1
List<Person> ls2
类(class)人员:
public class Person {
String name;
String id;
}
ls1 具有包含名称的 person 类,ls2 具有名称和 ID。 我需要做的是按名称匹配列表,然后将 ID 从 ls2 复制到 ls1。
除了在 ls1 中为每个人构建 for 循环并在 ls2 中找到它之外,最有效的方法是什么?我怎样才能更快地匹配它们?
最佳答案
使用list2构建一个map,遍历list1并检查map中是否存在,然后复制数据。这是Java 8中的解决方案
final Map<String, Person> personByName = lis2.stream().collect(Collectors.toMap(Person::getName, Function.identity()));
lis1.forEach(person -> {
final Person personFromMap= personByName.get(person.getName());
if(Objects.nonNull(personFromMap)){
//copy id, assuming a setId/getId method exist
person.setId(personFromMap.getId());
}
});
关于java - 按值匹配类列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41103715/