LoginSignup
0
3

More than 3 years have passed since last update.

【Java】HashMapの最大値を取得する方法

Posted at

開発環境・バージョン

・ホストOS: Windows10 Home
・ゲストOS: WSL2 Ubuntu20.04
・Java8

目的

keyの型がString, valueの型がIntegerのHashMapの最大値を取得すること

EntrySetメソッドを使って実装します。
以下は実際のコード


public static void main(String[] args) {
  String arr[] = {"a", "a", "a", "a", "b", "b", "b", "c", "c", "d"};
  Map<String, Integer> map = new HashMap<>();

//配列の要素をマップに格納
  for (String string : arr) {
    if (map.get(string) == null) {
      map.put(string, 1);
    } else {
      map.put(string, map.get(string) + 1);
    }
  }

//最大値とそのときのキーを初期化
  String maxKey = null;
  Integer maxValue = 0;

//entrySetメソッドでマップのキーとValueを一つずつ取得
for (Map.Entry<String, Integer> entry : map.entrySet()) {

//最大値とValueを比較してValueが大きければ、そのときのキーとValueを代入
  if (entry.getValue() > maxValue) {
    maxKey = entry.getKey();
    maxValue = entry.getValue();
  }
}
System.out.println(maxKey + " : " + maxValue);

結果

a : 4

無事最大値を取得することができました。
最大値が複数あり全てを取得する場合はリストに格納すればよいでしょう。

entrySetのメリットは一度のループでキーとValueを両方取得できることですね。

0
3
8

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3