JAVA Hashtable 求最大值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5240013/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 10:09:30  来源:igfitidea点击:

JAVA Hashtable find maximum value

javahashtableenumerationmax

提问by Donal.Lynch.Msc

I want to find the largest value in a Hashtableof Integervalues. Is there any quick and efficient way to achieve this?

我想在 a Hashtableof Integervalues 中找到最大值。有什么快速有效的方法来实现这一目标吗?

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 Hashtablewill always be small, less than 100 entries on average.

我需要找到最大值,在上面的例子中是5. 的Hashtable永远是小,平均不到100个条目。

回答by BalusC

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

使用Collections#max()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().

请注意,您应该使用Map#put()来放置元素,没有Map#add().

回答by user unknown

a) don't you write

a) 你不写

h.put ("a", 1); 

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

b) 你不能得到这样的值:

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

Now search the values.

现在搜索值。

回答by Abdullah Jibaly

Another approach:

另一种方法:

new TreeSet(h.values()).last()