Javaマップの最大値に関連付けられたキーを見つける質問する

Javaマップの最大値に関連付けられたキーを見つける質問する

マップ内の最大値に関連付けられたキーを取得する最も簡単な方法は何ですか?

最大値に対応するキーが必要な場合、Collections.max(someMap) は最大キーを返すと思います。

ベストアンサー1

完全を期すために、ここにやり方

最もクリーンな方法:

Collections.max(map.entrySet(), Map.Entry.comparingByValue()).getKey()

または

countMap.entrySet().stream().max((entry1, entry2) -> entry1.getValue() > entry2.getValue() ? 1 : -1).get().getKey();

または

Collections.max(countMap.entrySet(), (entry1, entry2) -> entry1.getValue() - entry2.getValue()).getKey();

または

Collections.max(countMap.entrySet(), Comparator.comparingInt(Map.Entry::getValue)).getKey();

おすすめ記事