使用Java Stream从Set of Sets中收集所有对象

13
我正在尝试学习Java Streams,试图从一个HashSet<SortedSet<Person>>中获取一个HashSet<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

我真正想要的是将所有老师和学生组合在一个HashSet<Person>中。 我猜我在收集我的流时做错了什么?

1个回答

13
你可以使用 flatMap 方法,将每个学生及其老师组成的流扁平化:
HashSet<Person> combined = 
    students.stream()
            .flatMap(student -> Stream.concat(Stream.of(student), student.getTeachers().stream()))
            .collect(Collectors.toCollection(HashSet::new));

concat用于将教师的流与由学生本身生成的流(使用of获得)连接起来。


9
首先,我想问的是,是否一定要使用HashSet,或者任何类型的Set都可以。除此之外,我还会降低嵌套操作的工作量。由于HashSettoSet()未指定结果类型都不维护排序,因此您可以将学生作为整体连接起来,而不是将每个学生作为嵌套的单例流:Set<Person> combined = Stream.concat(students.stream(), students.stream().flatMap(student -> student.getTeachers().stream())).collect(Collectors.toSet()); - Holger
2
@Holger为什么不把那个变成一个答案呢? - djeikyb
11
作为对我自己的提醒,如果一个人只想将一组简单的集合转化为一个集合,只需使用简单的 Set combined = set.stream().flatMap(Collection:stream).collect(Collectors.toSet()); 即可。 - eis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接