简体   繁体   English

如何使用lambda获取哈希映射中值的键数

[英]How to get the count of keys for values in a hash map using lambda

I have a hash map 我有一个哈希映射

Map<Integer, List<String>> Directmap = new HashMap<Integer, List<String>>() {{
    put(0, Arrays.asList(a, b));
    put(1, Arrays.asList(b, c));
    put(2, Arrays.asList(d));
    put(3, Arrays.asList(d, e));
    put(4, Arrays.asList(e));
    put(5, Arrays.asList());
}};

Directmap: {0=[a, b], 1=[b, c], 2=[d], 3=[d, e], 4=[e], 5=[]}

I want to count the number of keys for each value. 我想计算每个值的键数。 For example: "a" has one key, "b" has two keys, ..., "e" has two keys namely 3 and 4. 例如: "a"有一个键, "b"有两个键,......, "e"有两个键,即3和4。

I tried something like this: 我试过这样的事情:

Map<Object, Long> ex = Directmap.entrySet().stream()
            .collect(Collectors.groupingBy(e -> e.getKey(), Collectors.counting()));

I want the values with number of keys as the output. 我希望带有键数的值作为输出。 Like this : 像这样 :

a=[1], b=[2], c=[1], d=[2], e=[2]

You can do this by flat mapping each value of the map. 您可以通过平面映射地图的每个值来完成此操作。

In this code, only the values of the map are kept (since you are not interested in the keys). 在此代码中,仅保留映射的值(因为您对键不感兴趣)。 Each value, which is a List<String> is flat mapped so that the Stream pipeline, which is Stream<List<String>> becomes Stream<String> . 每个值( List<String>都是平面映射的,因此Stream管道( Stream<List<String>>变为Stream<String> Finally, the Stream is grouped by ( groupingBy ) the identity function and the reduction performed on the elements is just counting the number of occurences ( counting() ). 最后,Stream通过( groupingBy )对身份函数进行groupingBy ,对元素执行的减少只是计算出现次数( counting() )。

Map<String, Long> ex = 
      Directmap.values()
               .stream()
               .flatMap(Collection::stream)
               .collect(Collectors.groupingBy(v -> v, Collectors.counting()));

Note that if a value is appearing twice in the initial map, it will also counted twice. 请注意,如果某个值在初始地图中出现两次,则它也会计算两次。 If you want to count the number of distinct values, you can add a call to distinct() before collecting the result (or use a Set instead of a List ). 如果要计算不同值的数量,可以在收集结果之前添加对distinct()的调用(或使用Set而不是List )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM