1
2

More than 3 years have passed since last update.

【Java】Mapのキーと値のペアを拡張for文を使って取得する

Posted at

はじめに

Map のキーと値のペアをMap.entrySetを使って取得する方法です。
Map のキーと値を取得する方法は他にもkeySetvaluesがあります。
これらはキー・値のどちらかを取得するだけですが、entrySetを使うとキーと値のペアを取得することが出来ます。

entry.Set の使い方

Mapに値を設定

        Map<String,String> animal = new HashMap<>();
        animal.put("monkey", "猿");
        animal.put("dog", "犬");
        animal.put("cat", "猫");

Mapのキーと値のペアを取得

以下の処理ではentrySetメソッドを使用してキーと値のペアを取得し、getKeyメソッドでキーを、getValueメソッドで値を取得しています。

          for (Map.Entry<String, String> animalNameInJapanese : animal.entrySet()) {

            System.out.println(animalName.getKey() + "は日本語で" + animalName.getValue() + "です。");
        }

出力

monkeyは日本語で猿です。
dogは日本語で犬です。
catは日本語で猫です。

参照

Map Java Platform SE8 #entrySet

1
2
0

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
1
2