【问题标题】:Java: Transforming List<List> into a MapJava:将 List<List> 转换为 Map
【发布时间】:2019-09-24 20:58:41
【问题描述】:

给定一个唯一值子列表的列表(也就是说两个不同的子列表不能共享相同值的元素) - 例如:

List[List[1, 1, 1], List[2], List[4, 4], List[7]]

如何将其转换为具有(值、大小)键值对的 Map?

这将导致:

{
  1 : 3
  2 : 1
  4 : 2
  7 : 1
}

将我们的列表定义为values,我假设可以使用流并像这样收集地图:

values.stream().collect(Collectors.toMap(Integer::intValue, ? ));

目前不确定为第二个参数输入什么,因为它需要value mapper,但不允许在任何子列表上调用.size()

【问题讨论】:

  • 当输入为List[List[1, 1, 1, 6], List[2], List[4, 4], List[7, 6]] 时,预期的输出是什么?预计是{1:4,2:1,4:2,7:2} 还是{1:3,2:1,4:2,6:2,7:1}
  • @Naman 我们假设输入仅包含在其各自列表中具有相等值元素的列表。 List[1, 1, 1, 6] 不符合此描述。
  • 好的,那么考虑输入List[List[1, 1, 1], List[2], List[4, 4], List[7], List[1, 1],你现在期望输出是什么?
  • 你提出了很好的边缘案例 - 我将更新我的问题以注意任何两个子列表中的元素之间的唯一性,不包括它自己。

标签: java dictionary java-stream


【解决方案1】:

使用Collectors.toMap时,需要指定如何从流的每个元素中获取key和value。 Integer::intValue 在这里不起作用,因为您的流元素是列表,而不是整数。

对于键,获取列表的第一个元素。 (这假设内部列表都是非空的。)对于值,传递size 方法引用。

values.stream()
    .collect(Collectors.toMap(list -> list.get(0), List::size));

【讨论】:

【解决方案2】:

您可以展平列表,然后使用 Collectors.groupingBy(Function.identity(), Collectors.counting()) 之类的东西。 但是在这种情况下,我会说一个好的旧(嵌套)for 循环可能更易于编写和阅读。

List<List<Integer>> lst = Arrays.asList(Arrays.asList(1,1,1),Arrays.asList(2),Arrays.asList(4,4),Arrays.asList(7));

Map<Integer,Integer> result= new HashMap<Integer,Integer>();
System.out.println(lst);
//[[1, 1, 1], [2], [4, 4], [7]]

for(List<Integer> sub:lst){
  for(int n:sub){
    Integer last=result.get(n);
    int newCount=(last==null?0:last)+1;
    result.put(n, newCount);
  }
}
System.out.println(result);
//{1=3, 2=1, 4=2, 7=1}

【讨论】:

    【解决方案3】:

    我认为@rgettman's answer 是最优雅的。但是,它假定所有列表都是非空的。当然,这很容易解决,只需在 collect 缩减操作之前添加 .filter(list -&gt; !list.isEmpty())

    这是另一种方法,它不再将列表视为“二维”,即List&lt;List&lt;Integer&gt;&gt;,而是将其扁平化为Integers 的流。

    Map<Integer, Long> map = lists.stream()
        .flatMap(Collection::stream)
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
    

    【讨论】:

    • 当输入为List[List[1, 1, 1, 6], List[2], List[4, 4], List[7, 6]] 时,预期的输出是什么真的很重要。这种情况下的输出在两个答案中会有所不同。
    • 这确实产生了完全不同的结果。目前,所有发布的答案都存在这种异常情况。
    猜你喜欢
    • 2021-02-23
    • 1970-01-01
    • 2019-01-23
    • 2015-03-20
    • 2019-07-31
    • 1970-01-01
    • 2017-07-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多