uraza uraza - 1 year ago 76
Java Question

Collect all objects from a Set of Sets with Java Stream

I'm trying to learn Java Streams and trying to get a

from a

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 it to combine all teachers and all students in one
. I guess I'm doing something wrong when I'm collecting my stream?

Answer Source

You can flatMap each student into a stream formed by the student along with their teachers:

HashSet<Person> combined = 
            .flatMap(student -> Stream.concat(Stream.of(student), student.getTeachers().stream()))

concat is used to concatenate to the Stream of the teachers, a Stream formed by the student itself, obtained with of.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download