Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count how many HashMap entries have a given value

Tags:

java

hashmap

key

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

like image 358
user1621988 Avatar asked Sep 01 '12 08:09

user1621988


People also ask

How get number of items in HashMap?

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

How do you calculate map value?

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.

How do you count the number of occurrences of an element in a HashMap 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.

How many elements are in a HashMap Java?

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.


1 Answers

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}
like image 141
Adam Avatar answered Oct 02 '22 14:10

Adam