亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Java - 將帶有列表變量的對象轉換為對象列表

Java - 將帶有列表變量的對象轉換為對象列表

一只斗牛犬 2022-05-12 15:47:27
我的基礎課是: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?
查看完整描述

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


查看完整回答
反對 回復 2022-05-12
?
慕碼人8056858

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


查看完整回答
反對 回復 2022-05-12
  • 2 回答
  • 0 關注
  • 213 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號