Map循环嵌套的四种遍历方式

首先看一下集合的存储,map3的键值为0和1(这里是为了方便),然后value值分别又是一个map,那么来我们看一下分别用单纯的keySet和entrySet依靠迭代器进行遍历,然后是foreach配和keySet及entrySet遍历集合。

直接看代码吧:

import java.util.*;
//import java.util.Map.Entry;

public class MapMapTest {
    public static void main(String[] args) {
        Map map1 = new HashMap<>();
        map1.put("001","qwer");
        map1.put("002","asdf");
        Map map2 = new HashMap<>();
        map2.put("001","ujikol");
        map2.put("002","123456");
        Map> map3 = new HashMap<>();
        map3.put("0",map1);
        map3.put("1",map2);
        keySet1(map3);
        entrySet1(map3);
        keySet2(map3);
        entrySet(map3);
    }

    public static void keySet1(Map> map3) {
        Set st1 = map3.keySet();
        Iterator it1 = st1.iterator();
        while (it1.hasNext()) {
            String arr1 = it1.next();
            Map map1 = map3.get(arr1);
            Set st2 = map1.keySet();
            Iterator it2 = st2.iterator();
            while (it2.hasNext()) {
                String arr2 = it2.next();
                String arr3 = map1.get(arr2);
                System.out.println(arr1 + "..." + arr2 + "..." + arr3);
            }
        }
    }

    public static void entrySet1(Map> map3) {
        Set>> map1 = map3.entrySet();
        Iterator>> it1 = map1.iterator();
        while (it1.hasNext()) {
            Map.Entry> entry = it1.next();
            String arr1 = entry.getKey();
            Map map2 = entry.getValue();
            Set> map4 = map2.entrySet();
            Iterator> it2 = map4.iterator();
            while (it2.hasNext()) {
                Map.Entry entry2 = it2.next();
                String arr2 = entry2.getKey();
                String arr3 = entry2.getValue();
                System.out.println(arr1 + "..." + arr2 + "..." + arr3);
            }
        }
    }
    public static void keySet2(Map> map3) {
        for(Object o1 : map3.keySet()) {
            String arr1 = (String) o1;
            Map map1 = map3.get(arr1);
            for(Object o2 : map1.keySet()) {
                String arr2 = (String) o2;
                String arr3 = map1.get(arr2);
                System.out.println(arr1 + "..." + arr2 + "..." + arr3);
            }
        }
    }

    public static void entrySet(Map> map3) {
        for(Object o1 : map3.entrySet()) {
            Map.Entry> map1 = (Map.Entry>) o1;
            String arr1 = map1.getKey();
            Map map2 = map1.getValue();
            for(Object o2 : map2.entrySet()) {
                Map.Entry map = (Map.Entry) o2;
                String arr2 = map.getKey();
                String arr3 = map.getValue();
                System.out.println(arr1 + "..." + arr2 + "..." + arr3);
            }
        }
    }
}

运行结果如下:(四个都一样)

0...001...qwer
0...002...asdf
1...001...ujikol
1...002...123456

可以说集合的嵌套遍历确实有点麻烦,尽量还是用foreach,起码代码量少。(新手,勿喷)

 

 

 

你可能感兴趣的:(Map循环嵌套的四种遍历方式)