遵循map,将两个键值对都作为字符串,编写一个逻辑来过滤Map中的所有空值,而无需使用任何外部API?
除了遍历整个地图并过滤掉值(遍历整个地图并获取入口对象并丢弃这些对)之外,还有其他方法吗?
Map<String,String> map = new HashMap<String,String>();
map.put("1", "One");
map.put("2", "Two");
map.put("3", null);
map.put("4", "Four");
map.put("5", null);
//Logic to filer values
//Post filtering It should print only ( 1,2 & 4 pair )
您可以使用 Java 8 方法Collection.removeIf
来实现此目的:
map.values().removeIf(Objects::isNull);
这将删除所有空值。
在线演示
这是通过以下事实来工作的:为 HashMap 调用 .values()
会返回一个将修改委托回 HashMap 本身的集合,这意味着我们对 removeIf()
的调用实际上改变了 HashMap(这并不适用于所有 java Map)
如果您使用的是 Java 8 之前的版本,则可以使用:
Collection<String> values = map.values();
while (values.remove(null)) {}
这是有效的,因为HashMap.values()
返回值的视图,并且:
集合 [由
HashMap.values()
返回] 支持元素删除,它通过 Iterator.remove、Set.remove、removeAll、retainAll 和 clear 操作从映射中删除相应的映射
另一种可能更快的方法,因为您不必不断重复集合来查找第一个 null 元素:
for (Iterator<?> it = map.values().iterator();
it.hasNext();) {
if (it.next() == null) {
it.remove();
}
}
或者你可以在没有显式迭代的情况下做到这一点:
values.removeAll(Collections.singleton(null));
这将起作用
Map<String, String> result = map.entrySet()
.stream()
.filter(e -> e.getValue() != null)
.collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));