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

Vavr - turn List of Lists into single List

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

应该return:

flattened: List(one, two, three, for)
true

您可以将 StreamflatMap 一起使用:

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

使用 Vavr,您不需要 JDK:

的所有 stream/collect 样板
List<Object> result = list2.flatMap(o -> o instanceof List ? ((List) o) : List.of(o));