常用的Map集合遍历

第一种  map.entrySet()

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

        Map<String, String> map = new HashMap();
        map.put("key", "demo");
        map.put("key1", "demo1");

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

第二种  Iterator迭代器

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

        Map<String, String> map = new HashMap();
        map.put("key", "demo");
        map.put("key1", "demo1");
        map.put("key2", "demo2");

        Iterator iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            System.out.println(entry.getKey() + "=====" + entry.getValue());
        }

    }
}

第三种  个人认为巨笨的方法 

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

        Map<String, String> map = new HashMap();
        map.put("key", "demo");
        map.put("key1", "demo1");
        map.put("key2", "demo2");

        Iterator iterator = map.keySet().iterator();

        while (iterator.hasNext()) {
            //取出key
            String key = iterator.next().toString();
            System.out.println(key);
            //通过key拿到value
            String str = map.get(key);
            System.out.println(str);

        }

    }
}
发布了30 篇原创文章 · 获赞 32 · 访问量 620

猜你喜欢

转载自blog.csdn.net/weixin_42081445/article/details/105126856