英文:
Remove entries from Map after comparing keys from a Set
问题
我有一个 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");
        // 从 map 中移除。
        iterator.remove();
    }
}
如何在 Java 8 中更简洁地实现这个功能呢?
英文:
I've one Map<Long, String> & one Set<Long>.
Say,
Map<Long, String> mapA
Set<Long> setB
I want to remove those entries from mapA, whose keys are not in setB.
Also I want to print log for all the entries which have been removed from mapA.
Currently I'm using iterator.
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();
    }
}
How can I do it more concisely using Java8?
答案1
得分: 2
你可以像这样使用流:
mapA.entrySet().removeIf(e -> {
    if (setB.contains(e.getKey())) {
        return true;
    }
    LOGGER.error(e.getKey() + " 不存在");
    return false;
});
或者更好的是,如果你不需要值,可以调用keySet:
mapA.keySet().removeIf(k -> {
    if (setB.contains(k)) {
        return true;
    }
    LOGGER.error(k + " 不存在");
    return false;
});
英文:
You can use streams like this;
mapA.entrySet().removeIf(e -> {
    if(setB.contains(e.getKey())){
        return true;
    }
    LOGGER.error(e.getKey() + " does not exist");
    return false;
});
Or mush better you can call the keySet, if you don't need the values:
mapA.keySet().removeIf(k -> {
    if (setB.contains(k)) {
        return true;
    }
    LOGGER.error(k + " does not exist");
    return false;
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论