Collect all objects from a collection set with a Java stream

I am trying to learn Java threads and trying to get HashSet<Person>from HashSet<SortedSet<Person>>.

HashSet<Person> students = getAllStudents();
HashSet<SortedSet<Person>> teachersForStudents = students.stream().map(Person::getTeachers).collect(Collectors.toCollection(HashSet::new));
HashSet<Person> = //combine teachers and students in one HashSet

What I really want is to bring all the teachers and all the students together into one HashSet<Person>. I think I'm doing something wrong when I collect my flow?

+4
source share
1 answer

You can flatMapeach student in a stream formed by the student along with his teachers:

HashSet<Person> combined = 
    students.stream()
            .flatMap(student -> Stream.concat(Stream.of(student), student.getTeachers().stream()))
            .collect(Collectors.toCollection(HashSet::new));

concatused to unite in the stream of Masters, a stream formed by the student himself, obtained with the help of of.

+4
source

Source: https://habr.com/ru/post/1654442/


All Articles