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

标签 java hashmap counting

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

相关文章:

java - 使用HashMap动态改变jTable

java - Eclipse生成的hashCode函数好用吗?

google-sheets - 计算Google表格中每第n行单元格中出现的次数

algorithm - 删除图中的节点可以形成的树数

java - 是否可以使用双引号字符作为 HashMap 键的一部分?

python - 使用计数比率的附加列对 DataFrame 进行分组和旋转

java - 如果没有主机模式,从 docker 到 localhost 的 mysql 的 jdbc url 无法工作

java - 向 Guava ImmutableList 添加和删除项目

java - 如何解决无法识别的类问题?

java - 按顺序从 Cassandra 检索结果