2 回答

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超7個(gè)贊
一種方法是根據(jù)條件對(duì)當(dāng)前的 s 列表進(jìn)行分區(qū),Student如果其中的類為空或不為空
Map<Boolean, List<Student>> conditionalPartitioning = students.stream()
.collect(Collectors.partitioningBy(student -> student.getClasses().isEmpty(), Collectors.toList()));
然后進(jìn)一步使用這個(gè)分區(qū)到flatMap一個(gè)新學(xué)生列表中,因?yàn)樗麄兝锩嬗姓n程,并將concat它們與另一個(gè)分區(qū)一起使用,最終收集到結(jié)果中:
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貢獻(xiàn)1803條經(jīng)驗(yàn) 獲得超6個(gè)贊
是的,您應(yīng)該能夠執(zhí)行以下操作:
Student student = ?
List<Student> output =
student
.getClasses()
.stream()
.map(clazz -> new Student(student.getName, student.getClassName, clazz))
.collect(Collectors.toList());
對(duì)于一個(gè)學(xué)生。對(duì)于一群學(xué)生來說,這有點(diǎn)復(fù)雜:
(由于@nullpointer 評(píng)論中的觀察而更新。謝謝?。?/p>
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());
添加回答
舉報(bào)