zoukankan      html  css  js  c++  java
  • Java HashMap 遍历方式探讨

    JDK8之前,可以使用keySet或者entrySet来遍历HashMap,JDK8中引入了map.foreach来进行遍历。
    
    keySet其实是遍历了2次,一次是转为Iterator对象,另一次是从hashMap中取出key所对应的value。而entrySet只是遍历了一次就把key和value都放到了entry中,效率更高。如果是JDK8,使用Map.foreach方法。
    
    1. keySet和entrySet
    
    1.1 基本用法
    
    keySet:
    
    Map map=new HashMap();
    Iterator it=map.keySet().iterator();
    Object key;
    Object value;
    while(it.hasNext()){
    key=it.next();
    value=map.get(key);
    System.out.println(key+":"+value);
    }
    
    entrySet:
    
    Map map=new HashMap();
    Iterator it=map.entrySet().iterator();
    Object key;
    Object value;
    while(it.hasNext()){
    Map.Entry entry = (Map.Entry)it.next();
    key=entry.getKey();
    value=entry.getValue();
    System.out.println(key+"="+value);
    }
    2. Map.foreach
    
    在JDK8以后,引入了Map.foreach。
    
    Map.foreach本质仍然是entrySet
    
    default void forEach(BiConsumer<? super K, ? super V> action) {
            Objects.requireNonNull(action);
            for (Map.Entry<K, V> entry : entrySet()) {
                K k;
                V v;
                try {
                    k = entry.getKey();
                    v = entry.getValue();
                } catch(IllegalStateException ise) {
                    // this usually means the entry is no longer in the map.
                    throw new ConcurrentModificationException(ise);
                }
                action.accept(k, v);
            }
        }
    
    配合lambda表达式一起使用,操作起来更加方便。
    
    2.1 使用Java8的foreach+lambda表达式遍历Map
    
    Map<String, Integer> items = new HashMap<>();
    items.put("A", 10);
    items.put("B", 20);
    items.put("C", 30);
    items.put("D", 40);
    items.put("E", 50);
    items.put("F", 60);
     
    items.forEach((k,v)->System.out.println("Item : " + k + " Count : " + v));
     
    items.forEach((k,v)->{
        System.out.println("Item : " + k + " Count : " + v);
        if("E".equals(k)){
            System.out.println("Hello E");
        }
    });
    

      

  • 相关阅读:
    mysql替代like模糊查询的方法
    8个超实用的jQuery插件应用
    判断登陆设备是否为手机
    SQL tp3.2 批量更新 saveAll
    SQL-批量插入和批量更新
    防止手机端底部导航被搜索框顶起
    php COM
    thinkphp3.2 where 条件查询 复查的查询语句
    Form表单提交,js验证
    jupyter notebook 使用cmd命令窗口打开
  • 原文地址:https://www.cnblogs.com/ipetergo/p/7421163.html
Copyright © 2011-2022 走看看