Collect all objects from a Set of Sets with Java Stream
12,965
You can flatMap
each student into a stream formed by the student along with their teachers:
HashSet<Person> combined =
students.stream()
.flatMap(student -> Stream.concat(Stream.of(student), student.getTeachers().stream()))
.collect(Collectors.toCollection(HashSet::new));
concat
is used to concatenate to the Stream of the teachers, a Stream formed by the student itself, obtained with of
.
Related videos on Youtube
Author by
uraza
Updated on September 15, 2022Comments
-
uraza over 1 year
I'm trying to learn Java Streams and trying to get a
HashSet<Person>
from aHashSet<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 it to combine all teachers and all students in one
HashSet<Person>
. I guess I'm doing something wrong when I'm collecting my stream? -
Holger over 7 yearsThe first thing, I’d ask, is, whether it really has to be a
HashSet
or if anySet
would do. Besides that, I’d reduce the workload of the nested operation. Since neitherHashSet
nor the unspecified result type oftoSet()
maintain an ordering, you can just concat’ the students as a whole rather than each student as a nested singleton stream:Set<Person> combined = Stream.concat(students.stream(), students.stream().flatMap(student -> student.getTeachers().stream())) .collect(Collectors.toSet());
-
djeikyb over 7 years@Holger why not make that an answer?
-
eis about 5 yearsas a reminder to myself, if one just wants a simple set of sets to one set, just a simple
Set combined = set.stream().flatMap(Collection:stream).collect(Collectors.toSet());
will do