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