gpt4 book ai didi

java - 计算 map 中值的出现次数

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:03:31 25 4
gpt4 key购买 nike

我有以下类型的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com