I have a Hashtable in java like below and I’m trying to get the key that has the minimum value. Obviously I can iterate through all the elements to find it but is there an easier way to do it?
Hashtable<Object, Integer> hash= new Hashtable<Object, Integer>();
Using a Hashtable, no. But you could instead use aTreeMap.It has a method
firstKey()which provides the exact functionality you want.Grr, values, not keys. No, then you will need to iterate.
I’d say in that case you should use a separate Map (Multimap?) to store the reverse association.
whenever you put
key,valuesomething intohash, also putvalue,keyintoreverse.then retrieve the lowest value using
reverse.keySet().first()(this solution requires Guava)