Collect all objects from a Set of Sets with Java Stream

安稳与你 提交于 2019-12-04 06:20:59

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!