zoukankan      html  css  js  c++  java
  • Java中遍历ConcurrentHashMap的四种方式

    //方式一:在for-each循环中使用entries来遍历
    
    System.out.println("方式一:在for-each循环中使用entries来遍历");
    
    for(Map.Entry<String, String> entry: map.entrySet()) {
    
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
    
    }
    //方法二:在for-each循环中遍历keys或values,这种方式适用于需要值或者键的情况,方法二比方法一快了10%
    
    System.out.println("方法二:在for-each循环中遍历keys或values,这种方式适用于需要值或者键的情况");
    
    //遍历键
    
    for(String key : map.keySet()) {
    
    System.out.println("key = " + key);
    
    } 
    //遍历值
    
    for(String value : map.values()) {
    
    System.out.println("value = " + value);
    
    }
    //方法三:使用Iterator遍历,使用并发集合不会报异常,性能类似于方法二
    
    //使用泛型
    
    Iterator<Map.Entry<String, String>> entries = map.entrySet().iterator();
    
    System.out.println("使用Iterator遍历,并且使用泛型:");
    
    while (entries.hasNext()) {
     
    Map.Entry<String, String> entry = entries.next();
     
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
     
    //注意这里操作了集合,下面的的遍历不会再打印0
    
    if("0".equals(entry.getKey())) {
    
    map.remove(entry.getKey());
    
    }
    
    }
     
    //不使用泛型
    
    Iterator entrys = map.entrySet().iterator();
    
    System.out.println("使用Iterator遍历,并且不使用泛型");
    
    while (entrys.hasNext()) {
     
    Map.Entry entry = (Map.Entry) entrys.next();
     
    String key = (String)entry.getKey();
     
    String value = (String)entry.getValue();
     
    System.out.println("Key = " + key + ", Value = " + value);
     
    }
    //方式四:通过键找值遍历,该方法效率相当低,不建议使用
    
    System.out.println("方式四:通过键找值遍历");
    
    for (String key : map.keySet()) {
     
    String value = map.get(key);
     
    System.out.println("Key = " + key + ", Value = " + value);
     
    }
    
    }
  • 相关阅读:
    在某个点上弹出层
    根据表名、过程名、视图名查找对应的数据库
    js时间转换nan问题 兼容浏览器
    过滤html标记 以及 返回顶部
    自定义控件 加入include 报错 问题
    在有索引视图的表上新增、修改、删除 报错 set ARITHABORT 选项不对
    访微博代码
    兼容问题 链接不跳转
    js上下滚动代码
    onload问题
  • 原文地址:https://www.cnblogs.com/franson-2016/p/11769710.html
Copyright © 2011-2022 走看看