Create a nested parent child list in Java 8

user3378550 :

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> 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>

How this can be done in Java 8 streams?

tsolakp :

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() ) 
        ) 
    )
;

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=441917&siteId=1