public final static HashMap<String, Integer> party = new HashMap<String, Integer>();
party.put("Jan",1);
party.put("John",1);
party.put("Brian",1);
party.put("Dave",1);
party.put("David",2);
How can I return a number of how many people has the value 1
Use the size() method to get the count of elements.
map count() function in C++ STL Return Value: The function returns the number of times the key K is present in the map container. It returns 1 if the key is present in the container as the map only contains a unique key. It returns 0 if the key is not present in the map container.
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.
A HashMap in Java can have a maximum of 2^30 buckets for storing entries - this is because the bucket-assignment technique used by java. util. HashMap requires the number of buckets to be a power of 2, and since ints are signed in Java, the maximum positive value is 2^31 - 1, so the maximum power of 2 is 2^30.
I'd just use the Collections.frequency() method on the HashMap values, like this.
int count = Collections.frequency(party.values(), 1);
System.out.println(count);
===> 4
Or the general solution, generate a map of frequency against number.
Map<Integer, Integer> counts = new HashMap<Integer, Integer>();
for (Integer c : party.values()) {
int value = counts.get(c) == null ? 0 : counts.get(c);
counts.put(c, value + 1);
}
System.out.println(counts);
==> {1=4, 2=1}
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