【问题标题】:Stream collect list to map [duplicate]流收集列表以映射[重复]
【发布时间】:2018-07-04 15:22:31
【问题描述】:

我有这个代码:

    List<String> list = Arrays.asList("a", "b", "c", "a", "c");
    Map<String, List<String>> map = list.stream().collect(Collectors.groupingBy(
    Function.identity() ,
    Collectors.toCollection(ArrayList::new)
    ));

它产生的是什么

  {a=[a, a], b=[b], c=[c, c]}

请问我应该如何编写映射方法来获得可以给我的地图:

{a=2, b=1, c=2}

【问题讨论】:

  • 您可以先将Map&lt;String, List&lt;String&gt;&gt; map 更改为Map&lt;String, Integer&gt; map - 因为您不想要String(s) 的列表。

标签: java java-stream


【解决方案1】:

使用Collectors.counting

list.stream().collect(Collectors.groupingBy(
            Function.identity(), Collectors.counting()));

上面会给你一个Map&lt;String, Long&gt;

【讨论】:

    猜你喜欢
    • 2017-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-26
    相关资源
    最近更新 更多