java - 比较 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 更简洁地做到这一点?
解决方案
您可以使用这样的流;
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;
});
推荐阅读
- objective-c - CGGlyphs 位置错误
- apache-spark - 如何同时运行 Spark SQL JDBC/ODBC 服务器和 pyspark?
- python - Pandas 在排除时有条件地创建
- c# - Xamarin.Forms 自定义控件 AmbiguousMatchException
- python - 无法在 python 中同时使用加载和加载命令打开 JSON 文件
- c# - 局域网多人游戏场景更改
- asp.net-core - Microsoft.Extensions.Logging 中是否提供强制日志记录
- angular-material - Angular Material 元素/字体对于桌面使用来说太大了
- android - 完全禁用音频插孔作为媒体输出
- javascript - 有人能解释一下 React Native 语法“render() {...}”吗?