使用Collections获取HashMap中的最大值的键 [英] Get the key for the maximum value in a HashMap using Collections

查看:79
本文介绍了使用Collections获取HashMap中的最大值的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个任意对象的HashMap,具有 Double 值作为值: HashMap< MyObject,Double>myMap = new HashMap<>(); .我可以使用 Collections.max(myMap.values()); HashMap 中获得最大的 Double 值,但是我需要获取相应的值该值的关键.是否可以使用 Collections API做到这一点的简便方法,还是需要迭代器?我已经考虑过要获取最大值的位置,然后查询HashMap的位置并获取键,但是我不确定该怎么做.

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.

如果需要,我可以将类型从 HashMap 更改为其他类型,但是这两种类型(对象和双精度)需要保持不变.

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.

推荐答案

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

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

这篇关于使用Collections获取HashMap中的最大值的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆