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?
You could use: if((pairs. getKey()). equals("A")) i++; instead.
Use the size() method to get the count of elements.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With