2 回答
TA貢獻1829條經驗 獲得超7個贊
一種方法是根據條件對當前的 s 列表進行分區,Student如果其中的類為空或不為空
Map<Boolean, List<Student>> conditionalPartitioning = students.stream()
.collect(Collectors.partitioningBy(student -> student.getClasses().isEmpty(), Collectors.toList()));
然后進一步使用這個分區到flatMap一個新學生列表中,因為他們里面有課程,并將concat它們與另一個分區一起使用,最終收集到結果中:
List<Student> result = Stream.concat(
conditionalPartitioning.get(Boolean.FALSE).stream() // classes as a list
.flatMap(student -> student.getClasses() // flatmap based on each class
.stream().map(clazz -> new Student(student.getName(), clazz))),
conditionalPartitioning.get(Boolean.TRUE).stream()) // with classes.size = 0
.collect(Collectors.toList());
TA貢獻1803條經驗 獲得超6個贊
是的,您應該能夠執行以下操作:
Student student = ?
List<Student> output =
student
.getClasses()
.stream()
.map(clazz -> new Student(student.getName, student.getClassName, clazz))
.collect(Collectors.toList());
對于一個學生。對于一群學生來說,這有點復雜:
(由于@nullpointer 評論中的觀察而更新。謝謝!)
List<Student> listOfStudents = getStudents();
List<Student> outputStudents =
listOfStudents
.stream()
.flatMap(student -> {
List<String> classes = student.getClasses();
if (classes.isEmpty()) return ImmutableList.of(student).stream();
return classes.stream().map(clazz -> new Student(student.getName(), student.getClassName(), ImmutableList.of(clazz)));
})
.collect(Collectors.toList());
添加回答
舉報
