-1

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

2 回答 2

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());
于 2019-02-05T10:19:25.970 回答
2

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

List<Object> result = list2.flatMap(o -> o instanceof List ? ((List) o) : List.of(o));
于 2019-02-09T22:28:03.027 回答