LoginSignup
0
3

More than 1 year has passed since last update.

【Java】二次元Map: キーと値のペアを全て取得する

Posted at

Mapとは

Mapとは、キーと値のペアをリスト形式で保持するコレクションのことである。
取り出したい値のキーを指定することでその値を取得することができるが、Mapに格納されている全てのキーと値を取り出すにはどうしたらいいのだろうか

一次元Map: キーと値のペアを全て取得する

MapSample1.java
package sample;

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

public class MapSample1 {
    public static void main(String[] args) {

        Map<Integer, String> map = new HashMap<>();
        map.put(1, "aaa");
        map.put(6, "bbb");
        map.put(3, "ccc");

        for (Map.Entry<Integer, String> entry : map.entrySet()) {
            System.out.println(entry.getKey() + ":" + entry.getValue());
        }
    }
}


結果
1:aaa
3:ccc
6:bbb

二次元Map: キーと値のペアを全て取得する

やり方は一次元Mapのときと同様

MapSample2.java
package sample;

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

public class MapSample2 {
    public static void main(String[] args) {

        Map<Integer, Map<Integer, String>> map_list = new HashMap<Integer, Map<Integer, String>>();

        Map<Integer, String> map1 = new HashMap<>();
        map1.put(11, "aaa");
        map1.put(12, "bbb");
        map1.put(16, "ccc");

        Map<Integer, String> map2 = new HashMap<>();
        map2.put(21, "ddd");
        map2.put(24, "eee");
        map2.put(26, "fff");

        Map<Integer, String> map3 = new HashMap<>();
        map3.put(31, "ggg");
        map3.put(32, "hhh");
        map3.put(36, "iii");

        map_list.put(1, map1);
        map_list.put(2, map2);
        map_list.put(3, map3);

        for (Map.Entry<Integer, Map<Integer, String>> map : map_list.entrySet()) {

            for (Map.Entry<Integer, String> entry : map.getValue().entrySet()) {
                System.out.println(entry.getKey() + ": " + entry.getValue());
            }
            System.out.println();
        }

    }
}

結果
16: ccc
11: aaa
12: bbb

21: ddd
24: eee
26: fff

32: hhh
36: iii
31: ggg

以上

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