我正在尝试学习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>
中。 我猜我在收集我的流时做错了什么?
HashSet
,或者任何类型的Set
都可以。除此之外,我还会降低嵌套操作的工作量。由于HashSet
和toSet()
未指定结果类型都不维护排序,因此您可以将学生作为整体连接起来,而不是将每个学生作为嵌套的单例流:Set<Person> combined = Stream.concat(students.stream(), students.stream().flatMap(student -> student.getTeachers().stream())).collect(Collectors.toSet());
- HolgerSet combined = set.stream().flatMap(Collection:stream).collect(Collectors.toSet());
即可。 - eis