Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count occurrences of value in a map

I have a map of the following type:

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

The keys go from 1 - n. The subMap inside the entireMap is of the following type:

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

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 = ..."}}

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).

How can I do that?

like image 865
sHarivaRi Avatar asked Jun 12 '17 13:06

sHarivaRi


People also ask

How do you count the number of keys on a map?

You could use: if((pairs. getKey()). equals("A")) i++; instead.

How do you count elements in a HashMap?

Use the size() method to get the count of elements.

How do you count the number of occurrences of an element in a map in Java?

Count the occurrences of an element in an array in Java As a first step we will be creating a HashMap “countMap” to hold the element (Key) and the count as the value. For each of the element in the input array, check if it is present in the countMap, using containsKey() method.


1 Answers

Here is an example of an implementation.

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);

Output:

{Ceasar=2, Arthur=1, Bela=3}
3
like image 194
solomkinmv Avatar answered Sep 25 '22 13:09

solomkinmv