Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the keys with the biggest values from a hashmap?

Tags:

java

hashmap

I have a HashMap defined like this...

HashMap<String,Integer> uniqueNames = new HashMap<String,Integer>();

It stores a name, and the occurence of that name. For example...

uniqueNames.put("lastname",42);

How can I get the name with the highest occurrence?

For some more information, I'm working with a binary search tree of "people", storing the unique names and frequencies in a HashMap. What I want to do is to print the most common last names, and someone told me to use HashMap as I wanted to store a String together with an Integer. Maybe I should use a class to store the name and frequency instead? Could someone please offer some suggestions.

like image 403
steven Avatar asked Sep 21 '11 11:09

steven


People also ask

How do I return the size of a HashMap?

HashMap. size() method of HashMap class is used to get the size of the map which refers to the number of the key-value pair or mappings in the Map. Parameters: The method does not take any parameters. Return Value: The method returns the size of the map which also means the number of key-value pairs present in the map.


2 Answers

If you have to use a HashMap, then the simplest way is probabably just to loop through the Map looking for the maximum

Entry<String,Integer> maxEntry = null;

for(Entry<String,Integer> entry : uniqueNames.entrySet()) {
    if (maxEntry == null || entry.getValue() > maxEntry.getValue()) {
        maxEntry = entry;
    }
}
// maxEntry should now contain the maximum,
like image 117
Tom Jefferys Avatar answered Sep 22 '22 05:09

Tom Jefferys


Most obvious, now allowing for multiple with largest occurrence value:

Integer largestVal = null;
List<Entry<String, Integer>> largestList = new ArrayList<Entry<String, Integer>>();
for (Entry<String, Integer> i : uniqueNames.entrySet()){
     if (largestVal == null || largestVal  < i.getValue()){
         largestVal = i.getValue();
         largestList .clear();
         largestList .add(i);
     }else if (largestVal == i.getValue()){
         largestList .add(i);
     }
}

Another option would be to use Guava's BiMap.

BiMap<String, Integer> uniqueNames = ...;
List<Integer> values = Lists.newArrayList(uniqueNames.values());
Collections.sort(values);
String name = uniqueNames.inverse().get(values.get(0));
like image 37
John B Avatar answered Sep 18 '22 05:09

John B