Get the key for the maximum value in a HashMap using Collections [duplicate]

元气小坏坏 提交于 2020-07-23 05:22:05

问题


I have a HashMap of arbitrary objects, with Double values as the value: HashMap<MyObject, Double> myMap = new HashMap<>();. I can get the maximum Double value in the HashMap using Collections.max(myMap.values()); but I need to get the corresponding key for that value. Is there an easy way to do this with the Collections API it or would I need an iterator? I've thought about getting the position of the max value and then querying the HashMap for that position and get the key but I'm not sure how to do that.

EDIT: I can change the type from a HashMap to something else if necessary, but those two types (Object and Double) need to stay the same.


回答1:


Just iterate the entry set looking for the largest value:

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.

or, if you want to get all keys with maximal value:

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());
  }
}



回答2:


2 things here.

1) There is no way to get your key with Collections framework by giving it's value. You would need an iterator.

2) Telling the same, keys are unique and not values. You have to handle the case of duplicated values.



来源:https://stackoverflow.com/questions/35938842/get-the-key-for-the-maximum-value-in-a-hashmap-using-collections

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!