「Java」forEachでHashMapのkey、value(オブジェクト)を取得するサンプル

1.Userクラスの定義

package com.example;

public class User {

      protected String username;
      protected int age;

      public User(String username, int age) {
            this.username = username;
            this.age = age;

      }

      public String getUsername() {
            return username;
      }

      public void setUsername(String username) {
            this.username = username;
      }

      public int getAge() {
            return age;
      }

      public void setAge(int age) {
            this.age = age;
      }

}

2.Mapのkey、valueを取得

package com.example;

import java.util.HashMap;
import java.util.Map;

public class HashMapLoop {

      public static void main(String[] args) {
            HashMap<String, User> map = new HashMap<String, User>();
            map.put("U001", new User("yamada", 21));
            map.put("U002", new User("oosakai", 32));
            map.put("U003", new User("masumoto", 42));

		// forEach
		System.out.println("*****foreach start*****");
		map.forEach((k, v) -> {
			System.out.println("Key:" + k + " 名前: " + v.getUsername() + " 年齢: " + v.getAge());
		});
		System.out.println("*****foreach end*****");


      }

}

3.実行結果

*****foreach start*****
Key:U003 名前: masumoto 年齢: 42
Key:U002 名前: oosakai 年齢: 32
Key:U001 名前: yamada 年齢: 21
*****foreach end*****

Java

Posted by arkgame