JAVA Hashtable find maximum value

11,621

Solution 1

Use Collections#max() on Map#values().

int max = Collections.max(h.values());

Note that you should be using Map#put() to put the elements, there's no Map#add().

Solution 2

a) don't you write

h.put ("a", 1); 

b) Can't you get the values like this:

java.util.Collection <Integer> ci = h.values (); 
// [1, 5, 3, 5, 2, 1] 

Now search the values.

Share:
11,621
NiqT
Author by

NiqT

Hi! Donal is my name and I've been a Web Developer since 2009. My passion in life is making webpages for millions of people to enjoy and playing with the latest technologies is the best bit! Feel free to get in touch with me, but please, no spam..

Updated on June 04, 2022

Comments

  • NiqT
    NiqT almost 2 years

    I want to find the largest value in a Hashtable of Integer values. Is there any quick and efficient way to achieve this?

    This is my code...

    Hashtable<String,Integer> h = new Hashtable<String,Integer>();
    
    h.add( "a",1 );
    h.add( "b",5 );
    h.add( "c",3 );
    h.add( "d",5 );
    h.add( "e",2 );
    h.add( "f",1 );
    
    int max = ???;
    

    I need to find the maximum value, which in the example above is 5. The Hashtable will always be small, less than 100 entries on average.

  • z7sg Ѫ
    z7sg Ѫ about 13 years
    But it will always be slower than iterating through the values.