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

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

Vavr - 將列表列表轉換為單個列表

Vavr - 將列表列表轉換為單個列表

斯蒂芬大帝 2022-06-04 17:06:20
我有兩個 vavr 列表:List<Object> list1 = List.of("one", "two", "three", "for");List<Object> list2 = List.of("one", "two", List.of("three", "for"));如何將 轉換list2為等于list1?編輯我試圖解釋更多我想要達到的目標:System.out.println("list1: " + list1);System.out.println("list2: " + list2);輸出:list1: List(one, two, three, for)list2: List(one, two, List(three, for))我想展平 中的所有內部列表list2,因此展平的列表應等于list1:System.out.println("flattened: " + flattened);System.out.println(list1.equals(flattened));應該返回:flattened: List(one, two, three, for)true
查看完整描述

2 回答

?
江戶川亂折騰

TA貢獻1851條經驗 獲得超5個贊

您可以使用Streamwith flatMap:


List<Object> flattened =

    list2.stream()

         .flatMap(e -> ((e instanceof List) ? ((List<Object>)e).stream() : Stream.of(e)))

         .collect(Collectors.toList());

System.out.println(flattened);

System.out.println(list1.equals(flattened));

輸出:


[one, two, three, four]

true

編輯:


由于 OP 使用的是不同的List,這里有一個類似的解決方案io.vavr.collection.List:


List<Object> flattened =

    list2.toStream()

         .flatMap(e -> ((e instanceof List) ? ((List<Object>)e).toStream() : Stream.of(e)))

         .collect(List.collector());


查看完整回答
反對 回復 2022-06-04
?
拉丁的傳說

TA貢獻1789條經驗 獲得超8個贊

使用 Vavr,您不需要 JDK 的所有流/收集樣板:

List<Object> result = list2.flatMap(o -> o instanceof List ? ((List) o) : List.of(o));



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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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