Java 如何从 HashMap<String, String> 过滤“空”值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35863581/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to filter "Null" values from HashMap<String, String>?
提问by RaBa
Following map, having both key-value pair as String, Write a logic to filter all the null values from Map without using any external API's ?
在 map 之后,将两个键值对都作为 String,编写一个逻辑来过滤 Map 中的所有空值,而不使用任何外部 API ?
Is there any other approach than traversing through whole map and filtering out the values (Traversing whole map and getting Entry Object and discarding those pair) ?
除了遍历整个地图并过滤掉值(遍历整个地图并获取条目对象并丢弃那些对)之外,还有其他方法吗?
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 )
回答by Ferrybig
You can use the Java 8 method Collection.removeIf
for this purpose:
Collection.removeIf
为此,您可以使用 Java 8 方法:
map.values().removeIf(Objects::isNull);
This removed all values that are null.
这删除了所有为空的值。
This works by the fact that calling .values()
for a HashMap returns a collection that delegated modifications back to the HashMap itself, meaning that our call for removeIf()
actually changes the HashMap (this doesn't work on all java Map's)
这是因为调用.values()
HashMap 返回一个集合,该集合将修改委托回 HashMap 本身,这意味着我们的调用removeIf()
实际上更改了 HashMap(这不适用于所有 Java Map)
回答by jberndsen
that will work
那可行
Map<String, String> result = map.entrySet()
.stream()
.filter(e -> e.getValue() != null)
.collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
回答by Andy Turner
If you are using pre-Java 8, you can use:
如果您使用的是 Java 8 之前的版本,则可以使用:
Collection<String> values = map.values();
while (values.remove(null)) {}
This works because HashMap.values()
returns a view of the values, and:
这是有效的,因为HashMap.values()
返回值的视图,并且:
The collection [returned by
HashMap.values()
] supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations
集合 [returned by
HashMap.values()
] 支持元素移除,通过 Iterator.remove、Set.remove、removeAll、retainAll 和 clear 操作从映射中移除对应的映射
An alternative way that might be faster, because you don't have to keep re-iterating the collection to find the first null element:
一种可能更快的替代方法,因为您不必不断重新迭代集合以找到第一个空元素:
for (Iterator<?> it = map.values().iterator();
it.hasNext();) {
if (it.next() == null) {
it.remove();
}
}
Or you can do it without the explicit iteration:
或者您可以在没有显式迭代的情况下执行此操作:
values.removeAll(Collections.singleton(null));