I am new to Java 8 and need a solution to the below problem.
I have two classes as below:
class Person {
String name;
int age;
List
address;}
class Address {
String street;
String city;
String country;
}
Now I have a list coming from database like this:
List 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 findPerson;
adam
26
<123, xyz, 456>
<456, rrr, 123>
bill
31
<666, uuu, 999>
How this can be done in Java 8 streams?
解决方案
Another approach, won't require overriding equals and hashCode:
List 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() )
)
)
;