使用 Collections 获取 HashMap 中最大值的键

Tom*_*ley 2 java collections

我有一个任意对象的 HashMap,其Double值为 value: HashMap<MyObject, Double> myMap = new HashMap<>();。我可以在使用Double中获得最大值,但我需要获得该值对应的键。有没有一种简单的方法可以使用API 来做到这一点,或者我需要一个迭代器吗?我考虑过获取最大值的位置,然后在 HashMap 中查询该位置并获取密钥,但我不知道该怎么做。HashMapCollections.max(myMap.values());Collections

编辑:如果需要,我可以将类型从 a 更改HashMap为其他类型,但这两种类型(Object 和 Double)需要保持不变。

And*_*ner 5

只需迭代条目集寻找最大值即可:

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.
Run Code Online (Sandbox Code Playgroud)

或者,如果您想获取具有最大值的所有键:

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());
  }
}
Run Code Online (Sandbox Code Playgroud)