Collect all objects from a Set of Sets with Java Stream

前端 未结 1 1233
被撕碎了的回忆
被撕碎了的回忆 2021-02-15 19:55

I\'m trying to learn Java Streams and trying to get a HashSet from a HashSet>.

HashSet<         


        
1条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-15 20:05

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

    HashSet 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.

    0 讨论(0)
提交回复
热议问题