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>();
Hashtable. get() method of Hashtable class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the table contains no such mapping for the key.
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. Save this answer.
util. Hashtable. containsKey() method is used to check whether a particular key is present in the Hashtable or not. It takes the key element as a parameter and returns True if that element is present in the table.
So, it is O(1) to get smallest/largest element.
Using a Hashtable, no. But you could instead use a TreeMap
.
A Red-Black tree based
NavigableMap
implementation. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.
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.
Map<Object, Integer> hash= new Hashtable<Object, Integer>();
SortedSetMultimap<Integer, Object> reverse = TreeMultimap.create();
whenever you put key
, value
something into hash
, also put value
, key
into reverse
.
then retrieve the lowest value using reverse.keySet().first()
(this solution requires Guava)
Instead of iterating yourself you can use library function Collections.min(Collection,Comparator) over entrySet()
.
SAMPLE
public static void main(String[] args) {
HashMap<String,Integer> map = new HashMap<String,Integer>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);
System.out.println(
Collections.min(map.entrySet(), new Comparator<Map.Entry<String,Integer>>() {
@Override
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
return o1.getValue().intValue() - o2.getValue().intValue();
}})
.getKey()
);
}
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