第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

Java - 將帶有列表變量的對(duì)象轉(zhuǎn)換為對(duì)象列表

Java - 將帶有列表變量的對(duì)象轉(zhuǎn)換為對(duì)象列表

一只斗牛犬 2022-05-12 15:47:27
我的基礎(chǔ)課是: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"  },]為了簡(jiǎn)單起見,顯然是一個(gè)愚蠢的例子。我能夠做到這一點(diǎn)的唯一方法是通過一些冗長(zhǎng)的代碼,例如: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);  }});看看是否有辦法簡(jiǎn)化這一點(diǎn),也許使用flapMap?
查看完整描述

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


查看完整回答
反對(duì) 回復(fù) 2022-05-12
?
慕碼人8056858

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


查看完整回答
反對(duì) 回復(fù) 2022-05-12
  • 2 回答
  • 0 關(guān)注
  • 200 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)