【问题标题】:JAVA Hashtable find maximum valueJAVA Hashtable找到最大值
【发布时间】:2011-07-11 12:47:54
【问题描述】:

我想在HashtableInteger 值中找到最大值。有没有快速有效的方法来实现这一点?

这是我的代码...

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 = ???;

我需要找到最大值,在上面的例子中是5Hashtable 总是很小,平均少于 100 个条目。

【问题讨论】:

  • 遍历哈希表?

标签: java hashtable enumeration max


【解决方案1】:

a) 你不写

h.put ("a", 1); 

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

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

现在搜索值。

【讨论】:

    【解决方案2】:

    另一种方法:

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

    【讨论】:

    • 但它总是比遍历值要慢。
    【解决方案3】:

    Map#values() 上使用Collections#max()

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

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

    【讨论】:

      猜你喜欢
      • 2015-02-18
      • 1970-01-01
      • 2017-04-20
      • 1970-01-01
      • 2012-06-21
      • 1970-01-01
      • 2021-02-10
      • 1970-01-01
      • 2022-11-12
      相关资源
      最近更新 更多