Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Key for maximum value in Hashtable

Hi I have the following object:

Hashtable<Object, Double>

and I want to find the key of the maximum Double value in the table. Easiest way to do that?

Thanks

like image 433
chopchop Avatar asked Dec 20 '22 23:12

chopchop


1 Answers

There is no built in function to get the maximum value out of a Hashtable you are going to have to loop over all the keys and manually determine the max.

Object maxKey=null;
Double maxValue = Double.MIN_VALUE; 
for(Map.Entry<Object,Double> entry : table.entrySet()) {
     if(entry.getValue() > maxValue) {
         maxValue = entry.getValue();
         maxKey = entry.getKey();
     }
}

Edit: To find more than 1 key for the max value

ArrayList<Object> maxKeys= new ArrayList<Object>();
Double maxValue = Double.MIN_VALUE; 
for(Map.Entry<Object,Double> entry : table.entrySet()) {
     if(entry.getValue() > maxValue) {
         maxKeys.clear(); /* New max remove all current keys */
         maxKeys.add(entry.getKey());
         maxValue = entry.getValue();
     }
     else if(entry.getValue() == maxValue)
     {
       maxKeys.add(entry.getKey());
     }
}
like image 82
twain249 Avatar answered Jan 03 '23 18:01

twain249