【问题标题】:Java 8 Stream : convert a List<List<Integer>>Java 8 Stream:转换 List<List<Integer>>
【发布时间】:2021-10-13 11:50:41
【问题描述】:

我有一个这样的List&lt;List&lt;Integer&gt;&gt;

[
 [3, 12, 1, 14, 10],
 [3, 12, 1, 15, 10],
 [3, 13, 1, 12, 10],
 [3, 13, 1, 15, 10]
]

我想要这样的:(第一个元素只是 3,因为在前面的列表中,3 总是在第一位。第二个元素是 [12,13],因为在前面的列表中,12 和 13 在第二个索引等...)

[[3, [12,13], [1], [12,14,15], [10]]

Map&lt;Integer, List&lt;Integer&gt;&gt; 也是一个有价值的选择

Java 流可以做到这一点吗?

【问题讨论】:

  • 我不建议用流解决这个问题。原因是我们需要按顺序处理元素,而在使用流时不能保证这一点。有一些方法可以解决这个问题,但这些方法会使解决方案更加复杂。
  • 您的输出看起来不像Map&lt;Integer, List&lt;Integer&gt;&gt;。在您发布的方式中,它更像是Collection&lt;Set&lt;Integer&gt;&gt;

标签: arrays collections java-8 java-stream


【解决方案1】:

这是你的想法吗?这假定所有内部列表的大小相同。

List<List<Integer>> lists = List.of(
List.of(3, 12, 1, 14, 10),
List.of(3, 12, 1, 15, 10),
List.of(3, 13, 1, 12, 10),
List.of(3, 13, 1, 15, 10));
  • 流式传输内部列表的索引
  • 对于流中的每个列表,映射索引处的值。不要使用 distinct 重复值。
  • 收集列表中的内容
  • 并收集列表中的列表。
List<List<Integer>> result = IntStream.range(0,5)
        .mapToObj(i->lists.stream()
                .map(lst->lst.get(i))
                .distinct().toList())
        .toList();
System.out.println(result);

打印

[[3], [12, 13], [1], [14, 15, 12], [10]]

请注意,第四个列表没有排序,而是按照遇到值的顺序排列。如果需要,可以修复。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-16
    • 2023-03-26
    • 2022-07-05
    • 2018-02-18
    • 2010-09-06
    • 2016-12-26
    相关资源
    最近更新 更多