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?


一只斗牛犬
浏览 164回答 2
2回答

吃鸡游戏

一种方法是根据条件对当前的 s 列表进行分区,Student如果其中的类为空或不为空Map<Boolean, List<Student>> conditionalPartitioning = students.stream()&nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.partitioningBy(student -> student.getClasses().isEmpty(), Collectors.toList()));然后进一步使用这个分区到flatMap一个新学生列表中,因为他们里面有课程,并将concat它们与另一个分区一起使用,最终收集到结果中:List<Student> result = Stream.concat(&nbsp; &nbsp; &nbsp; &nbsp; conditionalPartitioning.get(Boolean.FALSE).stream() // classes as a list&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .flatMap(student -> student.getClasses() // flatmap based on each class&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .stream().map(clazz -> new Student(student.getName(), clazz))),&nbsp; &nbsp; &nbsp; &nbsp; conditionalPartitioning.get(Boolean.TRUE).stream()) // with classes.size = 0&nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toList());

慕码人8056858

是的,您应该能够执行以下操作:Student student = ?List<Student> output =&nbsp;&nbsp; &nbsp; student&nbsp; &nbsp; &nbsp; &nbsp; .getClasses()&nbsp; &nbsp; &nbsp; &nbsp; .stream()&nbsp; &nbsp; &nbsp; &nbsp; .map(clazz -> new Student(student.getName, student.getClassName, clazz))&nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toList());对于一个学生。对于一群学生来说,这有点复杂:(由于@nullpointer 评论中的观察而更新。谢谢!)List<Student> listOfStudents = getStudents();List<Student> outputStudents =&nbsp; &nbsp; listOfStudents&nbsp; &nbsp; &nbsp; &nbsp; .stream()&nbsp; &nbsp; &nbsp; &nbsp; .flatMap(student -> {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; List<String> classes = student.getClasses();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (classes.isEmpty()) return ImmutableList.of(student).stream();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return classes.stream().map(clazz -> new Student(student.getName(), student.getClassName(), ImmutableList.of(clazz)));&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toList());
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java