可以使用Map的keySet()方法获取Map中所有的key集合,然后遍历这个集合,如果当前的key不包含在List中,则将这个key对应的元素从Map中移除。

示例代码如下:

List<String> ids = Arrays.asList("1", "2", "3"); // ids列表
Map<String, Object> heartCheckMap = new HashMap<>(); // heartCheckMap
heartCheckMap.put("1", "value1");
heartCheckMap.put("2", "value2");
heartCheckMap.put("3", "value3");
heartCheckMap.put("4", "value4");
heartCheckMap.put("5", "value5");

Set<String> keysToRemove = new HashSet<>(); // 需要移除的key集合
for (String key : heartCheckMap.keySet()) {
    if (!ids.contains(key)) {
        keysToRemove.add(key);
    }
}

for (String key : keysToRemove) {
    heartCheckMap.remove(key);
}

运行后,Map中只剩下key为"1"、"2"、"3"的元素,其余元素已被移除

存在ListString ids列表和MapString Object heartCheckMap 如何比较list和map移除map中key不包含list的元素

原文地址: https://www.cveoy.top/t/topic/eDLS 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录