[英]How can I Merge two Lists of custom objects of a Different Type using Java 8
我有两个自定义对象列表。 我想按id
合并两个列表,使用 Java 8。
我有一个 class Employee
字段(所有字符串): id
, name
, city
。
我还有另一个 class Person
字段(所有字符串): id
, city
。
这是一个例子:
List<Employee> employeeList = Stream.of(
new Employee("100","Alex",""),
new Employee("200","Rida",""),
new Employee("300","Ganga",""))
.collect(Collectors.toList());
List<Person> personList = Stream.of(
new Person("100","Atlanta"),
new Person("300","Boston"),
new Person("400","Pleasanton"))
.collect(Collectors.toList());
合并两个列表后,我想得到如下所示的结果。
我该怎么做?
List<Employee>
[
Employee(id=100, name=Alex, city=Atlanta),
Employee(id=200, name=Rida, city=null),
Employee(id=300, name=Ganga, city=Boston),
Employee(id=400, name=null, city=Pleasanton)
]
为了实现这一点,首先,您可以使用id
作为键基于两个列表创建两个映射。
然后在这些映射的键集上创建一个 stream。 然后在map()
操作中,您需要为每个键创建一个新的Employee
object,方法是传递从personById
中提取的employeeList
city
中提取的name
。
当id
不存在于任何一个映射中时, get()
返回的 object 将是null
并且尝试在其上调用方法将触发NullPointerException
。 为了处理这种情况,我们可以使用空对象模式,通过定义两个可以安全访问的变量并将作为参数提供给getOfDefault()
。
然后使用Collectors.toList()
将 stream 元素收集到列表中。
public static void main(String[] args) {
List<Employee> employeeList = Stream.of(
new Employee("100","Alex",""),
new Employee("200","Rida",""),
new Employee("300","Ganga",""))
.collect(Collectors.toList());
List<Person> personList = Stream.of(
new Person("100","Atlanta"),
new Person("300","Boston"),
new Person("400","Pleasanton"))
.collect(Collectors.toList());
Map<String, Employee> employeeById = employeeList.stream()
.collect(Collectors.toMap(Employee::getId, Function.identity()));
Map<String, Person> personById = personList.stream()
.collect(Collectors.toMap(Person::getId, Function.identity()));
Person nullPerson = new Person("", null); // null-object
Employee nullEmployee = new Employee("", null, null); // null-object
List<Employee> result = Stream.concat(employeeById.keySet().stream(),
personById.keySet().stream())
.distinct() // eliminating duplicated keys
.map(key -> new Employee(key,
employeeById.getOrDefault(key, nullEmployee).getName(),
personById.getOrDefault(key, nullPerson).getCity()))
.collect(Collectors.toList());
result.forEach(System.out::println);
}
Output
Employee{id='100', name='Alex', city='Atlanta'}
Employee{id='200', name='Rida', city='null'}
Employee{id='300', name='Ganga', city='Boston'}
Employee{id='400', name='null', city='Pleasanton'}
不确定此处的 Employee class 是否扩展了 Person。 理想情况下,它应该。
Employee 可以是 Person,但并非所有 Person 都必须是 Employee。 因此,将其收集为List<Employee>
是没有意义的,因此。
理想情况下,您应该将其收集为List<Person>
并且 Employee 应该扩展 Person。 请重新查看您的 class 结构,而不是专注于将其收集为List<Employee>
,这应该可以解决您的问题。
您可以使用 stream 中的映射和分组,或按 ID 搜索第二个列表并将员工更新到第一个列表。 Java 不包含会自动合并不同对象的内置函数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.