本文介绍了计算地图中出现的价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下类型的地图:
private HashMap<Integer, HashMap<String, Object>> entireMap;
键从1到n.wholeMap内的subMap具有以下类型:
The keys go from 1 - n. The subMap inside the entireMap is of the following type:
HashMap<String, Object> subMap = new HashMap<String, Object>();
整个地图的每个键都包含此subMap(以及更多):
Every key of the entire map contains this subMap (and a lot more):
subMap.put("user_name", usid[1]);
所以我最后有这样的东西:
So i have something like this at the end:
{1 {"user_name" = "Arthur", "otherKeys = ..."}}
{2 {"user_name" = "Bela", "otherKeys = ..."}}
{3 {"user_name" = "Ceasar", "otherKeys = ..."}}
{4 {"user_name" = "Ceasar", "otherKeys = ..."}}
{5 {"user_name" = "Bela", "otherKeys = ..."}}
{6 {"user_name" = "Bela", "otherKeys = ..."}}
现在,我想计算整个地图中user_name的最大出现次数,在这种情况下,它将是3(重复出现3次).
Now I want to count the max occurence of a user_name in the entireMap, in this case it would be 3 (bela occures three times).
我该怎么做?
推荐答案
以下是实现示例.
注意:请勿在生产代码中使用此类地图初始化!
Note: don't use such map initialization in production code!
HashMap<Integer, HashMap<String, Object>> entireMap = new HashMap<>();
entireMap.put(1, new HashMap<String, Object>() {{
put("user_name", "Arthur");
put("other_key1", "val");
put("other_key2", "val");
}});
entireMap.put(2, new HashMap<String, Object>() {{
put("user_name", "Bela");
put("other_key2", "val");
}});
entireMap.put(3, new HashMap<String, Object>() {{
put("user_name", "Ceasar");
}});
entireMap.put(4, new HashMap<String, Object>() {{
put("user_name", "Ceasar");
}});
entireMap.put(5, new HashMap<String, Object>() {{
put("user_name", "Bela");
}});
entireMap.put(6, new HashMap<String, Object>() {{
put("user_name", "Bela");
}});
Map<Object, Long> result = entireMap
.values()
.stream()
.map(map -> map.get("user_name"))
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(result);
Long max = Collections.max(result.values());
System.out.println(max);
输出:
{Ceasar=2, Arthur=1, Bela=3}
3
这篇关于计算地图中出现的价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!