首页 > 解决方案 > 比较 Set 中的键后从 Map 中删除条目

问题描述

我有一个Map<Long, String>和一个Set<Long>

说,

Map<Long, String> mapA
Set<Long> setB

我想从中删除那些条目mapA,其键不在setB.

我还想打印所有已从mapA.

目前我正在使用迭代器。

for (Iterator<Map.Entry<Long, String>> iterator = mapA.entrySet().iterator();
     iterator.hasNext(); ) {

    Map.Entry<Long, String> entry = iterator.next();
    if (!setB.contains(entry.getKey())) {
        
        LOGGER.error(entry.getKey() + " does not exist");

        // Removing from map.
        iterator.remove();
    }
}

如何使用 Java8 更简洁地做到这一点?

标签: javacollections

解决方案


您可以使用这样的流;

mapA.entrySet().removeIf(e -> {
    if(setB.contains(e.getKey())){
        return true;
    }
    LOGGER.error(e.getKey() + " does not exist");
    return false;
});

或者更好的是,如果您不需要这些值,您可以调用 keySet:

mapA.keySet().removeIf(k -> {
    if (setB.contains(k)) {
        return true;
    }
    LOGGER.error(k + " does not exist");
    return false;
});

推荐阅读