Map中的forEach方法的使用

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

官方解释

/**
     * Performs the given action for each entry in this map until all entries
     * have been processed or the action throws an exception.   Unless
     * otherwise specified by the implementing class, actions are performed in
     * the order of entry set iteration (if an iteration order is specified.)
     * Exceptions thrown by the action are relayed to the caller.
     *
     * @implSpec
     * The default implementation is equivalent to, for this {@code map}:
     * <pre> {@code
     * for (Map.Entry<K, V> entry : map.entrySet())
     *     action.accept(entry.getKey(), entry.getValue());
     * }</pre>
     *
     * The default implementation makes no guarantees about synchronization
     * or atomicity properties of this method. Any implementation providing
     * atomicity guarantees must override this method and document its
     * concurrency properties.
     *
     * @param action The action to be performed for each entry
     * @throws NullPointerException if the specified action is null
     * @throws ConcurrentModificationException if an entry is found to be
     * removed during iteration
     * @since 1.8
     */

翻译

对该映射中的每个条目执行给定的操作,直到处理完所有条目或该操作引发异常为止。除非实现类另有指定,否则操作将按条目集迭代的顺序执行(如果指定了迭代顺序)。操作引发的异常将转发给调用方。
*
*@implSpec公司
*对于这个{@code map},默认实现相当于:
*<pre>{@代码
*forMap.Entry<KV>Entry:Map.entrySet())
*action.accept(entry.getKey(),entry.getValue());
*}</pre>
*
*默认实现不保证此方法的同步性或原子性属性。任何提供原子性保证的实现都必须重写此方法并记录其并发属性。
*
*@param action为每个条目执行的操作
*如果指定的操作为null@throws NullPointerException
*如果在迭代过程中发现某个条目被删除,@抛出ConcurrentModificationException
*@自1.8

使用方法

package test_0;

import java.util.HashMap;
import java.util.Map;
/**
 * @className: Map_1_8.java
 * @description: TODO map在JDK1.8之后与之前的不同应用
 * @author: LiXiangyu
 * @date: 2021年7月23日
 **/
public class Map_1_8 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
	      Map<Object, Object> map = new HashMap<>();
	      map.put("name", "sun");
	      map.put("phone", "18888888888");
	      map.put(null, null);
	      // 通用的Map迭代方式
	      System.out.println("==============Map的通用迭代======================");
	      for (Map.Entry<Object, Object> entry : map.entrySet()) {
	          System.out.println(entry.getKey() + ":" + entry.getValue());
	      }
	      System.out.println("==============Map的1.8迭代=====================");
	      Map<Object, Object> map8 = new HashMap<>();
	      map8.put(null, null);
	      map8.put("phone", "16666688888");
	      map8.put("sex", "男");
	      map8.put("name", "li");
	      // JDK8的迭代方式
	      map8.forEach((key, value) -> {
	          System.out.println(key + ":" + value);
	      });
	}
}

结果

结果

注:list中forEach不推荐add/remove

在迭代时使用add/remove易出bug。推荐使用Iterator进行迭代,操作list进行add/remove

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

猿小白888

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值