「Java」拡張for文でHashMapの要素(key,objectの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.Entry;

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));

            System.out.println("xxxxxxxx for start xxxxxxxx");
            // 拡張for文
            for (Entry<String, User> entry : map.entrySet()) {
                  System.out.println("key:" + entry.getKey());
                  System.out.println("名前:" + entry.getValue().getUsername());
                  System.out.println("年齢:" + entry.getValue().getAge());
            }
            System.out.println("xxxxxxxx for end xxxxxxxx");
      }

}

3.実行結果
xxxxxxxx for start xxxxxxxx
key:U003
名前:masumoto
年齢:42
key:U002
名前:oosakai
年齢:32
key:U001
名前:yamada
年齢:21
xxxxxxxx for end xxxxxxxx

Java

Posted by arkgame