Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get key of minimum value in a Hashtable

Tags:

java

hash

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>();
like image 728
MinaHany Avatar asked Oct 02 '12 14:10

MinaHany


People also ask

Can we get key from value in Hashtable?

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.

How do you find the maximum value in a Hashtable?

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.

How do you check if a Hashtable contains a key?

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.

What is the O complexity of finding the smallest key stored in a Hashtable?

So, it is O(1) to get smallest/largest element.


2 Answers

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)

like image 71
Sean Patrick Floyd Avatar answered Sep 21 '22 01:09

Sean Patrick Floyd


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


    );
}
like image 26
Suzan Cioc Avatar answered Sep 19 '22 01:09

Suzan Cioc