Map中的forEach方法

转载请标明出处^_^
原文首发于: www.zhangruibin.com
本文出自于: RebornChang的博客

HashMap

HashMap 继承于AbstractMap,实现了Map、Cloneable、java.io.Serializable接口。
AbstractMap实现了Map接口。
Map接口里面有一个forEach方法,@since 1.8。

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);
       }
   }

官方解释:
对此映射中的每个条目执行给定操作,直到所有条目已处理或操作引发异常。除非由实现类指定,操作将在入口集迭代的顺序(如果指定了迭代顺序)。
操作引发的异常将中继到调用方。

解读:
使用了try catch 抛出的异常为ConcurrentModificationException,标示在线程并发进行读写的时候会出现异常,即,不支持并发操作。

使用方法:

      Map<Object, Object> map = new HashMap<>();
      map.put("name", "RebornChang");
      map.put("gender", "男");
      map.put("phone", "18888888888");
      map.put(null, null);
      //1.Map的迭代
      // 通用的Map迭代方式
      System.out.println("==============Map的迭代======================");
      for (Map.Entry<Object, Object> entry : map.entrySet()) {
          System.out.println(entry.getKey() + ":" + entry.getValue());
      }
      System.out.println("====================================");
      // JDK8的迭代方式
      map.forEach((key, value) -> {
          System.out.println(key + ":" + value);
      });
      
      
      

结果:

        ==============Map的迭代======================
        null:null
        gender:男
        phone:18888888888
        name:RebornChang
        ====================================
        null:null
        gender:男
        phone:18888888888
        name:RebornChang

猜你喜欢

转载自blog.csdn.net/m0_37190495/article/details/93724306