我有一个任意对象的HashMap,Double
其值为:HashMap<MyObject, Double> myMap = new HashMap<>();
。我可以Double
在HashMap
使用中获得最大值,Collections.max(myMap.values());
但是我需要获取该值的对应键。有没有一种简单的方法可以使用Collections
API进行操作,还是需要迭代器?我已经考虑过要获取最大值的位置,然后查询HashMap的位置并获取键,但是我不确定该怎么做。
编辑:HashMap
如有必要,我可以将类型从a更改为其他类型,但是这两种类型(对象和双精度)需要保持相同。
只需迭代条目集以寻找最大值:
Map.Entry<MyObject, Double> maxEntry = null;
for (Map.Entry<MyObject, Double> entry : map.entrySet()) {
if (maxEntry == null || entry.getValue() > maxEntry.getValue()) {
maxEntry = entry;
}
}
MyObject maxKey = maxEntry.getKey(); // Might NPE if map is empty.
或者,如果要获取所有具有最大值的键:
double maxValue = null;
List<MyObject> maxKeys = new ArrayList<>();
for (Map.Entry<MyObject, Double> entry : map.entrySet()) {
if (maxValue == null || maxValue.equals(entry.getValue())) {
maxValue = entry.getValue();
maxKeys.add(entry.getKey());
} else if (entry.getValue() > maxValue) {
maxValue = entry.getValue();
maxKeys.clear();
maxKeys.add(entry.getKey());
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句