【Java】遍历 Map 时删除 Map 中元素

https://blog.csdn.net/LSKCGH/article/details/97521668
https://www.jianshu.com/p/a3b3aae6697c

不能直接在 Map 的 for 循环中使用 remove 方法,会抛出 ConcurrentModificationException 异常,应使用迭代器中的 remove 方法删除元素。

以下代码运行时会抛出 ConcurrentModificationException:

import java.util.HashMap;
import java.util.Map;

public class Test {
    public static void main(String[] args) {
        Map<Integer, Integer> map = new HashMap<>();
        //初始化map
        for (int i = 0; i < 10; i++) {
            map.put(i, i);
        }
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if (entry.getKey() == 1) {
                map.remove(entry.getKey());
            }
            System.out.println(entry.getKey() + " " + entry.getValue());
        }
    }
}

解决方案如下:

示例1:

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class Test {
    public static void main(String[] args) {
        Map<Integer, Integer> map = new HashMap<>();
        //初始化map
        for (int i = 0; i < 10; i++) {
            map.put(i, i);
        }
        Iterator<Map.Entry<Integer, Integer>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<Integer, Integer> next = iterator.next();
            int key = next.getKey();
            int value = next.getValue();
            if (key == 1) {
                iterator.remove();
            }
            System.out.println(key + " " + value);
        }
    }
}

示例2:

import java.util.*;

public class Test {
    public static void main(String[] args) {
        Map<String, Map<String, Long>> appIdChannelAgg = new HashMap<String, Map<String, Long>>() {{
            put("saf0", new HashMap<String, Long>() {{
                put("10", 454L);
            }});
            put("saf1", new HashMap<String, Long>() {{
                put("11", 454L);
            }});
            put("saf2", new HashMap<String, Long>() {{
                put("12", 454L);
            }});
        }};
        List<String> hzList = Arrays.asList("fas", "dfa", "saf0");
        Iterator<String> iterator = appIdChannelAgg.keySet().iterator();
        while (iterator.hasNext()) {
            String appId = iterator.next();
            if (!hzList.contains(appId)) {
                iterator.remove();
            }
        }
        System.out.println(appIdChannelAgg);
    }
}

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值