问题描述
我有一个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;
});
,
您可以使用[T]
,如下所示:
mapA.keySet().removeAll(set-of-keys-which-are-not-in-setB)
输出:
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Map<Long,String> mapA = new HashMap<>(Map.of(1L,"One",2L,"Two",3L,"Three",4L,"Four"));
Set<Long> setB = new HashSet<>(Set.of(1L,3L));
// Set of keys which are not in setB
Set<Long> temp = new HashSet<>(mapA.keySet());
temp.removeAll(setB);
mapA.keySet().removeAll(temp);
System.out.println(mapA);
}
}