Java 辞書(HashMap)の作成・使い方【初心者向け解説】

Javaで、辞書やマップ、キーバリューペアを作成するためにHashMapが使用できます。以下は辞書を作成して使用する例です:

  1. 辞書を表すHashMapオブジェクトを作成する。
HashMap<String, Integer> dictionary = new HashMap<>();

この例では、辞書のキーはString型で、値はInteger型です。

  1. 辞書にキーと値のペアを追加する。
dictionary.put("apple", 1);
dictionary.put("banana", 2);
dictionary.put("orange", 3);
  1. 辞書から値を取得する:
int appleValue = dictionary.get("apple");
System.out.println("The value of 'apple' is: " + appleValue);
  1. 辞書のすべてのキーと値のペアをループする。
for (Map.Entry<String, Integer> entry : dictionary.entrySet()) {
    System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}

Javaで辞書を作成してキーと値のペアを保存および検索することができます。Javaでは、HashMapは順序を持たないデータ構造ですが、順序のある辞書が必要な場合はTreeMapを使用することができます。

bannerAds