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());
添加回答
举报