获取地图的最小值(Key,Double) [英] Get minvalue of a Map(Key,Double)

查看:104
本文介绍了获取地图的最小值(Key,Double)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有方法(可能使用Google Collections)获取地图(键,双)的最小值

Is there a method (maybe with Google Collections) to obtain the min value of a Map(Key, Double)?

以传统的方式,我必须根据值对地图进行排序,然后取第一个/最后一个。

In the traditional way, I would have to sort the map according to the values, and take the first/last one.

推荐答案

您可以使用标准 收藏品#min()

You can use the standard Collections#min() for this.

Map<String, Double> map = new HashMap<String, Double>();
map.put("1.1", 1.1);
map.put("0.1", 0.1);
map.put("2.1", 2.1);

Double min = Collections.min(map.values());
System.out.println(min); // 0.1

更新:因为你也需要密钥,所以,我在 收藏 或Google Collections2 API,因为地图不是收集 Maps#filterEntries() 也没什么用处,因为你只知道实际的结果 end of iteration。

Update: since you need the key as well, well, I don't see ways in Collections or Google Collections2 API since a Map is not a Collection. The Maps#filterEntries() is also not really useful, since you only know the actual result at end of iteration.

最简单的解决方案是:

Entry<String, Double> min = null;
for (Entry<String, Double> entry : map.entrySet()) {
    if (min == null || min.getValue() > entry.getValue()) {
        min = entry;
    }
}

System.out.println(min.getKey()); // 0.1

min 左检查>一边)

这篇关于获取地图的最小值(Key,Double)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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