Map(Key,Double)の最小値を取得する 質問する

Map(Key,Double)の最小値を取得する 質問する

の最小値を取得する方法(おそらく Google Collections を使用)はありますかMap(Key, Double)

従来の方法では、値に応じてマップをソートし、最初/最後の値を取得する必要がありました。

ベストアンサー1

標準の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またはGoogleCollections2API はMapではないためCollectionMaps#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

(min左側に null チェック)

おすすめ記事