美文网首页
遍历Map几种方式

遍历Map几种方式

作者: simperLv | 来源:发表于2018-12-19 16:29 被阅读0次

    1、最常用的方式,加强for循环遍历键值

            Map<String,String> map2 = new HashMap<String,String>();
            map2.put("name1","王大");
            map2.put("name2","王二");
            map2.put("name3","王三");
            map2.put("name4","王四");
            //在键值都需要时使用
            for (Map.Entry<String,String> entry : map2.entrySet()){
                System.out.println(entry.getKey() +"==>"+ entry.getValue());
            }
    

    2、for-each循环中遍历keys或values

            for (String keyName : map2.keySet()){
                System.out.println(keyName);
            }
            for (String valueName : map2.values()){
                System.out.println(valueName);
            }
    

    3、通过键找值遍历

          for (String key4 : map2.keySet()){
                String value4 = map2.get(key4);
                System.out.println(key4 +"==>"+ value4);
            }
    

    4、使用Iterator遍历

           Map map = new HashMap();
           map.put("name1","王大");
           map.put("name2","王二");
           map.put("name3","王三");
           map.put("name4","王四");
           //不使用泛型
           Iterator iterator = map.keySet().iterator();
           Object key,value;
           while (iterator.hasNext()){
               key = iterator.next();
               value = map.get(key);
               System.out.println(key + "==>" + value);
           }
            //使用泛型
            Iterator<Map.Entry<String,String>> iterator2 = map2.entrySet().iterator();
            while (iterator2.hasNext()){
                Map.Entry<String,String> entry = iterator2.next();
                System.out.println(entry.getKey() + "==>" + entry.getValue());
            }
    

    5、使用java8新特性forEach+Lambda遍历

     map2.forEach((k,v)-> System.out.println(k+"的值为"+v));
    

    参考文章:https://www.cnblogs.com/fqfanqi/p/6187085.html

    相关文章

      网友评论

          本文标题:遍历Map几种方式

          本文链接:https://www.haomeiwen.com/subject/sjyjkqtx.html