0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Java】MapでforEachメソッドを使う方法

Last updated at Posted at 2021-05-09

はじめに

本記事では、Java8で追加されたListやMapなどを巡回(Iterate)するためのforEachメソッドについてアウトプットします。
以下ではMapを巡回するための方法について書きます。

#①Lambdaを使用する場合

Map<String, String> capitalsMap = new LinkedHashMap<>();
		capitalsMap.put("Paris", "France");
		capitalsMap.put("Beijin", "China");
		capitalsMap.put("Berlin", "Germany");
		capitalsMap.put("Canberra", "Australia");

		capitalsMap.forEach((k, v) -> {
		    System.out.println("key: " + k + ", value: " + v);
		});

##出力

key: Paris, value: France
key: Beijin, value: China
key: Berlin, value: Germany
key: Canberra, value: Australia

#②entrySetを使用する場合

Map<String, String> capitalsMap = new LinkedHashMap<>();
		capitalsMap.put("Paris", "France");
		capitalsMap.put("Beijin", "China");
		capitalsMap.put("Berlin", "Germany");
		capitalsMap.put("Canberra", "Australia");

		capitalsMap.entrySet().forEach(entry -> {
		    System.out.println("key: " + entry.getKey()
		            + ", value: " + entry.getValue());
		});

##出力

key: Paris, value: France
key: Beijin, value: China
key: Berlin, value: Germany
key: Canberra, value: Australia

まとめ

個人的にはentrySetを使った方が分かりやすいですが、
Lambdaを使った方がコードがスッキリして良いと思いました。

#参照
Java Platform SE8 #Map

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?