嗨,我有以下对象:
Hashtable<Object, Double>我想在表中找到最大双精度值的键。最简单的方法是什么?
谢谢
发布于 2012-04-04 12:56:13
没有内置的函数可以从Hashtable中获取最大值,您必须遍历所有键并手动确定最大值。
Object maxKey=null;
Double maxValue = Double.MIN_VALUE;
for(Map.Entry<Object,Double> entry : table.entrySet()) {
if(entry.getValue() > maxValue) {
maxValue = entry.getValue();
maxKey = entry.getKey();
}
}编辑:查找超过1个键的最大值
ArrayList<Object> maxKeys= new ArrayList<Object>();
Double maxValue = Double.MIN_VALUE;
for(Map.Entry<Object,Double> entry : table.entrySet()) {
if(entry.getValue() > maxValue) {
maxKeys.clear(); /* New max remove all current keys */
maxKeys.add(entry.getKey());
maxValue = entry.getValue();
}
else if(entry.getValue() == maxValue)
{
maxKeys.add(entry.getKey());
}
}发布于 2012-04-04 13:06:37
如果它真的很重要,您可以在不迭代所有键的情况下完成,只需扩展HashTable
class MyHashtable extends Hashtable<Object, Double> {
private Double maxValue = Double.MIN_VALUE;
@Override
public synchronized Double put(Object k, Double v) {
maxValue = Math.max(maxValue, v);
return super.put(k, v);
}
@Override
public synchronized void clear() {
super.clear();
maxValue = Double.MIN_VALUE;
}
public Double getMaxValue() {
return maxValue;
}
@Override
public synchronized Double remove(Object key) {
// TODO: Left as an Excercise for the user, refer the other answers
return super.remove(key);
}
}发布于 2012-04-04 12:57:52
您可以遍历并找到最大值:
public static void main(String[] args) {
Map<Object, Double> maps = new HashMap<Object, Double>();
maps.put("5", new Double(50.0));
maps.put("4", new Double(40.0));
maps.put("2", new Double(20.0));
maps.put("1", new Double(100.0));
maps.put("3", new Double(30.0));
maps.put("5", new Double(50.0));
Double max = Double.MIN_VALUE;
for(Object key: maps.keySet()) {
Double tmp = maps.get(key);
if(tmp.compareTo(max) > 0) {
max = tmp;
}
}
System.out.println(max);
}https://stackoverflow.com/questions/10005053
复制相似问题