在Java 8中创建嵌套的父子级列表 [英] Create a nested parent child list in Java 8
本文介绍了在Java 8中创建嵌套的父子级列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是Java 8的新手,需要解决以下问题.
I am new to Java 8 and need a solution to the below problem.
我有两个班级,如下:
class Person {
String name;
int age;
List<Address> address;
}
class Address {
String street;
String city;
String country;
}
现在我有一个来自数据库的列表,像这样:
Now I have a list coming from database like this:
List<Person> findPerson;
adam
26
<123, xyz, yyy>
adam
26
<456, rrr, kkk>
bill
31
<666, uuu, hhh>
现在我需要将同一个人对象与不同地址对象组合在一起,如下所示?
Now I need to combine the same person objects with different address objects in one, like below?
List<Person> findPerson;
adam
26
<123, xyz, 456>
<456, rrr, 123>
bill
31
<666, uuu, 999>
如何在Java 8流中完成此操作?
How this can be done in Java 8 streams?
推荐答案
另一种方法,不需要覆盖equals
和hashCode
:
Another approach, won't require overriding equals
and hashCode
:
List<Person> merged = findPerson.stream()
.collect(
Collectors.collectingAndThen(
Collectors.toMap(
(p) -> new AbstractMap.SimpleEntry<>( p.getName(), p.getAge() ),
Function.identity(),
(left, right) -> {
left.getAddress().addAll( right.getAddress() );
return left;
}
),
ps -> new ArrayList<>( ps.values() )
)
)
;
这篇关于在Java 8中创建嵌套的父子级列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文