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