Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collect all objects from a Set of Sets with Java Stream

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?

like image 971
uraza Avatar asked Sep 13 '16 09:09

uraza


People also ask

Can we use stream with set in java?

Stream can be converted into Set using forEach(). Loop through all elements of the stream using forEach() method and then use set. add() to add each elements into an empty set.

What does stream of () method in java?

Stream of(T t) returns a sequential Stream containing a single element. Parameters: This method accepts a mandatory parameter t which is the single element in the Stream. Return Value: Stream of(T t) returns a sequential Stream containing the single specified element.

Which method can be used to get the stream object from any collection?

The collect() method of Stream class can be used to accumulate elements of any Stream into a Collection.

Can we convert stream to List in java?

Stream class has toArray() method to convert Stream to Array, but there is no similar method to convert Stream to List or Set. Java has a design philosophy of providing conversion methods between new and old API classes e.g. when they introduced Path class in JDK 7, which is similar to java.


1 Answers

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.

like image 114
Tunaki Avatar answered Oct 13 '22 14:10

Tunaki