Java – 将具有列表变量的对象转换为对象列表

我的基本课程是:

public class Student {
  public String name;
  public String className; // In real code I'd have a second object for return to the end user
  public List<String> classes; // Can be zero
}

我想把它弄平,所以我可以回复一些类似的东西

[
  {
    "name":"joe",
    "class":"science"
  },
  {
    "name":"joe",
    "class":"math"
  },
]

为简单起见,显然是一个愚蠢的例子.

我能够做到的唯一方法是通过一些冗长的代码,例如:

List<Student> students = getStudents();
List<Student> outputStudents = new ArrayList<>();
students.forEach(student -> {
  if(student.getClasses().size() > 0) {
    student.getClasses().forEach(clazz -> {
      outputStudents.add(new Student(student.getName(), clazz));
    });
  } else {
    outputStudents.add(student);
  }
});

看看有没有办法简化这个,也许使用flapMap?

最佳答案
是的,你应该可以做这样的事情:

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());

转载注明原文:Java – 将具有列表变量的对象转换为对象列表 - 代码日志