获取地图的最小值(键,双精度)
问题内容:
是否有一种方法(也许使用Google收藏夹)来获取a的最小值Map(Key, Double)
?
以传统方式,我将不得不根据值对地图进行排序,并选择第一个/最后一个。
问题答案:
您可以Collections#min()
为此使用标准。
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
更新
:由于您也需要密钥,因此,我不会在Collections
Google
Collections2
API中看到任何方法,因为a
Map
不是a Collection
。该Maps#filterEntries()
也不是真正有用的,因为你只知道在实际的结果
结束 迭代。
那么,最直接的解决方案是:
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
(nullcheck在min
左侧)