我有一个任意对象的 HashMap,带有 Double
值作为值:HashMap<MyObject, Double> myMap = new HashMap<>();
.我可以获得最大值 Double
HashMap
中的值使用 Collections.max(myMap.values());
但我需要为该值获取相应的键。有没有一种简单的方法可以用 Collections
做到这一点? API它还是我需要一个迭代器?我考虑过获取最大值的位置,然后在 HashMap 中查询该位置并获取 key ,但我不确定该怎么做。
编辑:我可以从 HashMap
更改类型如有必要,可以更改为其他类型,但这两种类型(Object 和 Double)需要保持不变。
只是迭代条目集寻找最大值:
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());
}
}