zoukankan      html  css  js  c++  java
  • 关于Map集合的遍历总结

    Map集合的遍历经常遇到,今天在这里总结一下Map集合遍历的几种方式:

    1 public static void main(String[] args){
    2      Map<String,String> map=new  HashMap<String,String>();
    3     map.put("1","张三");
    4     map.put("2","李四");
    5     map.put("3","王五");
    6 
    7 }    
    1. 通过Map.keySet遍历key和value   
    1 for(String key:map.keySet()){
    2    System.out.print("key="+key);
    3     System.out.println("value="+map.get(key));
    4 
    5 }
    View Code

          2.通过Map.entrySet和迭代器遍历Map

        

    Iterator<Map.Entry<String,String>> car =map.entrySet().interator();
      while(car.hasNext()){
          Map.Entry<String,String>  entry=car.next();
         System.out.println("key="+entry.getKey()+"and value="+entry.getValue());
    
      }
    

     3.Map.entrySet()加for in 循环(推荐):

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

    注:Map.entrySet()返回的是一个Set<Map<k,v>>,Map.Entry是一个接口,表示一个键值对(映射项),而Set<Map<k,v>>则表示映射项的Set。

    4.通过Map.values():

    for(String val:map.Values()){
        System.out.println("value="+v);
    
    }

     5.lambda表达式(推荐)

     map.forEach((k,v)->{
         System.out.println("key: " + k + " value : " + v);
         if("E".equals(k)){
             System.out.println("Hello E");
         }
     });
    
  • 相关阅读:
    [hadoop](2) MapReducer:Distributed Cache
    [hadoop](1) MapReduce:ChainMapper
    hadoop平台搭建
    postgresql主从同步配置
    问题记录-java图片验证码显示乱码
    windows mongodb启动
    新的开始
    springboot和Redis整合
    springboot的简单热部署
    springmvc模式下的上传和下载
  • 原文地址:https://www.cnblogs.com/lsgspace/p/4666020.html
Copyright © 2011-2022 走看看