java中遍历MAP,嵌套map的几种方法

时间:2021-09-09 21:21:56

java中遍历MAP的几种方法
Map<String,String> map=new HashMap<String,String>();   

map.put("username", "qq");

map.put("passWord", "123");

map.put("userID", "1");

map.put("email", "qq@qq.com");

1.用for循环

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

2.用keySet()迭代

        Iterator<String> it=map.keySet().iterator();
        while(it.hasNext()){
  
         System.out.println("<<<<<<<<" +
it.next().toString() + ", " + map.get(it.next().toString()));
        }

3. 用entrySet()迭代

        Iterator<Entry<String, String>> it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> entry1 = it.next();
            System.out.println(entry1.getKey().toString() + "==" + entry1.getValue().toString());
        }

    public static void main(String[] a) {
        Map<String,Map<String,String>> requests = new HashMap<String, Map<String,String>>();
        Map<String,String> headers = new HashMap<String,String>();
        Map<String,String> cookies = new HashMap<String,String>();

        requests.put("header", headers);
        requests.put("cookie", cookies);
        headers.put("ua", "uaaaaaaaaaaaaaaaaaa");
        cookies.put("sessionid1", "sessionid1111111111");
        headers.put("accept", "acceptttttttttttttttt");
        cookies.put("sessionid2", "sessionid2222222222");

        Set<String> keySet = requests.keySet();
        for(Iterator<String> it = keySet.iterator();it.hasNext();) {
            String key = it.next();
            Map<String,String> map = requests.get(key);
            Set<Entry<String, String>> entrySet = map.entrySet();
            for(Iterator<Entry<String, String>> it2 = entrySet.iterator();it2.hasNext();) {
                Map.Entry<String, String> me = it2.next();
                System.out.println(key+"^"+me.getKey() + "^" + me.getValue());
            }
        }
    }