Map中根据key批量删除键值对

public static void main(String[] args) {
    Map<String,String> map = new HashMap<String,String> ();
    map.put("1", "a");
    map.put("2", "b");
    map.put("3", "c");
    
    Iterator iterator = map.keySet().iterator();
    while (iterator.hasNext()) {
        String key = (String) iterator.next();
        if ("1".equals(key) || "2".equals(key)) {
            iterator.remove();        //添加该行代码
            map.remove(key);
        }
    }
}

工具类

public class MapUtil {
    /**
     * Map中根据key批量删除键值对
     * @param map
     * @param excludeKeys
     * @param <K>
     * @param <V>
     * @return
     */
    public static <K, V> Map removeEntries(Map<K, V> map, K[] excludeKeys) {
        Iterator<K> iterator = map.keySet().iterator();
        while (iterator.hasNext()) {
            K key = iterator.next();
            // 如果key 刚好在要排除的key的范围中
            if (ArrayUtils.contains(excludeKeys, key)) {
                iterator.remove();
                map.remove(key);
            }
        }
        return map;
    }
}
MapUtil.removeEntries(map, new String[]{"1", "2"});
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值