私はJava Streamsを学び、取得しようとしています HashSet<Person>
から 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
すべての教師とすべての生徒を1つにまとめたい HashSet<Person>
。ストリームを収集しているときに何か間違ったことをしていると思いますか?
回答:
回答№1は4あなたはできる flatMap
生徒と教師が形成するストリームへの各生徒:
HashSet<Person> combined =
students.stream()
.flatMap(student -> Stream.concat(Stream.of(student), student.getTeachers().stream()))
.collect(Collectors.toCollection(HashSet::new));
concat
教師のストリームに連結するために使用され、生徒自身によって形成されたストリームは、 of
.