【问题标题】:Vavr - turn List of Lists into single ListVavr - 将列表列表转换为单个列表
【发布时间】:2019-02-05 10:16:32
【问题描述】:

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

【问题讨论】:

  • 你有没有尝试过?
  • 当然,我尝试了mapflatMaptransform,但无法成功。
  • 您的要求不清楚。 必须首先阐明您希望事物如何变得平等。它只是关于扁平化所有内部列表,还是只是你找到的第一个?您会看到:当您为两个列表调用 removeAll 时,它们也是相等的。
  • 我想展平所有内部列表,所以 list1.equals(list2) 应该返回 true。

标签: java collections vavr


【解决方案1】:

您可以将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,所以我在 list2 对象上没有 stream() 方法。
  • @kojot 您对List.of 的使用表明您使用的是 Java 9 或更高版本,因此您应该拥有 Streams。
  • 是的,但list2 不是java.util.List,它是io.vavr.collection.List
  • @kojot 可能并不真正相关,但你为什么首先使用 vavr?
  • @kojot 为什么不使用 JDK 中的不可变集合? Java-9 引入了不可变集合,例如 vavr 和 List.of()
【解决方案2】:

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

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

【讨论】:

  • 看起来更好的解决方案。
猜你喜欢
  • 2021-11-25
  • 2016-05-27
  • 1970-01-01
  • 1970-01-01
  • 2016-11-30
  • 2012-09-29
  • 2014-09-27
相关资源
最近更新 更多