Search code examples
javacollectionsjava-stream

Java Stream get some values from the Entity containing more than one collection


I have a problem about getting some values from more than one list in entity.

Here is the Person entity shown below.

Person

....

Set<Experience> experinences = new HashSet<Experience>()
Set<Education> educations = new HashSet<Education>()

....

Here is the Experience entity shown below.

Experience

....
name
description

Here is the Education entity shown below.

Education

.....
name
description

Here is the Dto shown below.

Dto

String experienceName;
String educationName;

What I want to do it to get only name of both experience and education from the entity through Java Stream. I knew flatmap is used for that but I have no idea how to do that in more than one collection.

How can I do that?


Solution

  • If you need to get a list of DTOs per Person instance where each education is paired with each experience like this:

    expOne    edu1
    expOne    edu2
    expOne    edu3
    expTwo    edu1
    expTwo    edu2
    expTwo    edu3
    

    It may be implemented as follows using flatMap:

    List<Dto> dtos = person.getExperiences()
        .stream()                 // Stream<Experience>
        .map(Experience::getName) // Stream<String> exp names
        .flatMap(expName -> person.getEducations()
                .stream()                // inner Stream<Education>
                .map(Education::getName) // Stream<String> edu names
                .map(eduName -> new Dto(expName, eduName)) // Stream<Dto>
        ) // Stream<Dto>
        .collect(Collectors.toList());