Key for maximum value in Hashtable

15,955

Solution 1

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());
     }
}

Solution 2

If it's really important you do it without iterating all keys, simply extend HashTable

class MyHashtable extends Hashtable<Object, Double> {

    private Double maxValue = Double.MIN_VALUE;

    @Override
    public synchronized Double put(Object k, Double v) {
        maxValue = Math.max(maxValue, v);
        return super.put(k, v);
    }

    @Override
    public synchronized void clear() {
        super.clear();
        maxValue = Double.MIN_VALUE;
    }

    public Double getMaxValue() {
        return maxValue;
    }

    @Override
    public synchronized Double remove(Object key) {
        // TODO: Left as an Excercise for the user, refer the other answers
        return super.remove(key);
    }
}
Share:
15,955
chopchop
Author by

chopchop

Updated on June 04, 2022

Comments

  • chopchop
    chopchop almost 2 years

    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

  • Learner
    Learner almost 11 years
    Can I know, what happens if their are two highest values?
  • Learner
    Learner almost 11 years
    what I am suppose to do to find both values key
  • Learner
    Learner almost 11 years
    Can I know, what happens if their are two highest values? what I am suppose to do to find both values key? thx in advance
  • twain249
    twain249 almost 11 years
    @Learner check the edit to handle multiple keys with the same max value
  • twain249
    twain249 almost 11 years
    This finds all the keys that replace the old maximum value. With your test set it should have returned 'c' and 'd' not 'b' and 'd'.
  • AnV
    AnV over 6 years
    your algorithm/code gives the wrong answer. As @twain249 said, it finds all keys that replace old max value. It should rather find a key which has max value or all the keys which have their value as max value.