我有以下类型的 map :
private HashMap<Integer, HashMap<String, Object>> entireMap;
键从 1 到 n。 entireMap里面的subMap是下面的类型:
HashMap<String, Object> subMap = new HashMap<String, Object>();
整个 map 的每个键都包含这个子 map (以及更多):
subMap.put("user_name", usid[1]);
所以我最后有这样的东西:
{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 在 entireMap 中的最大出现次数,在本例中为 3(bela occures 三次)。
我该怎么做?
最佳答案
这是一个实现示例。
注意:不要在生产代码中使用这样的 map 初始化!
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
关于java - 计算 map 中值的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44500446/