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?
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.
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.
The collect() method of Stream class can be used to accumulate elements of any Stream into a Collection.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With