JAVA Hashtable find maximum value
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 fi开发者_开发知识库nd the maximum value, which in the example above is 5
. The Hashtable
will always be small, less than 100 entries on average.
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()
.
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.
Another approach:
new TreeSet(h.values()).last()
精彩评论