猿问

Vavr - 将列表列表转换为单个列表

我有两个 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


斯蒂芬大帝
浏览 72回答 2
2回答

江户川乱折腾

您可以使用Streamwith flatMap:List<Object> flattened =&nbsp; &nbsp; list2.stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.flatMap(e -> ((e instanceof List) ? ((List<Object>)e).stream() : Stream.of(e)))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.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 =&nbsp; &nbsp; list2.toStream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.flatMap(e -> ((e instanceof List) ? ((List<Object>)e).toStream() : Stream.of(e)))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.collect(List.collector());

拉丁的传说

使用 Vavr,您不需要 JDK 的所有流/收集样板:List<Object>&nbsp;result&nbsp;=&nbsp;list2.flatMap(o&nbsp;->&nbsp;o&nbsp;instanceof&nbsp;List&nbsp;?&nbsp;((List)&nbsp;o)&nbsp;:&nbsp;List.of(o));
随时随地看视频慕课网APP

相关分类

Java
我要回答