我有兩個 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());

拉丁的傳說
TA貢獻1789條經驗 獲得超8個贊
使用 Vavr,您不需要 JDK 的所有流/收集樣板:
List<Object> result = list2.flatMap(o -> o instanceof List ? ((List) o) : List.of(o));
添加回答
舉報
0/150
提交
取消