码迷,mamicode.com
首页 > 编程语言 > 详细

Java中遍历Map的四种方式

时间:2019-03-10 20:36:51      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:alt   图片   mamicode   hash   png   inf   next   iter   out   

Demo如下

 Map<String, String> map = new HashMap<>();
        map.put("key1","data1");
        map.put("key2","data2");
        map.put("key3","data3");

        //第一种方式
        System.out.println("通过Map.keySet(),遍历key,value");
        for (String key :map.keySet()) {
            System.out.println("key:" + key + ",value:" + map.get(key));
        }

        //第二种方式
        System.out.println("通过map.entrySet().iterator(),遍历key,value");
        Iterator<Map.Entry<String,String>> it =  map.entrySet().iterator();
        while(it.hasNext()){
            Map.Entry<String,String> next  = it.next();
            System.out.println("key:" + next.getKey() + ",value:" + next.getValue());
        }

        //第三种方式
        System.out.println("通过Map.entrySet(),遍历key,value;推荐使用尤其是大容量时");
        for(Map.Entry<String,String> entry : map.entrySet()){
            System.out.println("key:" + entry.getKey() + ",value:" + entry.getValue());
        }

        //第四种方式
        System.out.println("通过Map.values(),遍历所有的Value,但不能遍历Key");
        for(String v : map.values()){
            System.out.println("所有的Value:" + v);
        }

控制台输出

技术图片

 

Java中遍历Map的四种方式

标签:alt   图片   mamicode   hash   png   inf   next   iter   out   

原文地址:https://www.cnblogs.com/dzcici/p/10506813.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!