计算地图中值的出现次数

Count occurrences of value in a map

我有一张以下类型的地图:

private HashMap<Integer, HashMap<String, Object>> entireMap;

按键从 1 到 n。 entireMap里面的subMap是下面的类型:

HashMap<String, Object> subMap = new HashMap<String, Object>();

整个地图的每个键都包含这个子地图(以及更多):

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 的最大出现次数,在本例中为 3(出现三次)。

我该怎么做?

这是一个实现示例。

注意: 不要在生产代码中使用这样的地图初始化!

    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 8 个功能,您可以通过简单地遍历地图来完成。

Map<String, Integer> resultMap = new HashMap<String, Integer>();

for (int key : entireMap.keySet()) {
    String userName = (String) entireMap.get(key).get("user_name");

    if (resultMap.containsKey(userName)) {
        resultMap.put(userName, resultMap.get(userName) + 1);
    } else {
        resultMap.put(userName, 1);
    }
}

System.out.println(resultMap);

输出:

{亚瑟=1,凯撒=2,贝拉=3}

这是使用 Java 8 个功能但不使用数据流的一种方法:

Map<String, Long> counts = new HashMap<>();
entireMap.forEach((k, v) ->
    counts.merge(v.get("user_name"), 1L, Long::sum));

counts 地图中,您将获得每个用户的计数。然后你可以找到具有最大值的条目:

Entry<String, Long> max = Collections.max(
    counts.entrySet(),
    Map.Entry.comparingByValue());

在 Java 7 或更低版本中,您可以使用 Guava MultiSet:

List<Object> names = new ArrayList<>();
for (HashMap<String, Object> outerMap : entireMap.values()) {
    names.add(outerMap.get("user_name"));
}

HashMultiset<Object> objects = HashMultiset.create(names);

objects.forEachEntry((name, count) -> System.out.println(name + " -> " + count));

结果:

Ceasar -> 2
Arthur -> 1
Bela -> 3