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.

Share:
12,965

Related videos on Youtube

uraza
Author by

uraza

Updated on September 15, 2022

Comments

  • uraza
    uraza over 1 year

    I'm trying to learn Java Streams and trying to get a HashSet<Person> from a 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 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
    Holger over 7 years
    The first thing, I’d ask, is, whether it really has to be a HashSet or if any Set would do. Besides that, I’d reduce the workload of the nested operation. Since neither HashSet nor the unspecified result type of toSet() 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
    djeikyb over 7 years
    @Holger why not make that an answer?
  • eis
    eis about 5 years
    as 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.t‌​oSet()); will do