[英]Java 8 Streams - Iterator Map and Remove based on conditions
I'm trying to figure out how I can rewrite this to use streams and filters to narrow my criteria down and remove from map if necessary.我试图弄清楚如何重写它以使用流和过滤器来缩小我的标准并在必要时从地图中删除。
Iterator<Map.Entry<String,Object>> iter = listOfPossibleParams.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String,Object> entry = iter.next();
if(entry.getValue() instanceof String) {
if (StringUtils.isBlank((String) entry.getValue())) {
iter.remove();
}
}
}
I was initially thinking something like this, but it obiviously doesnt work as syntax errors :我最初在想这样的事情,但显然它不能作为语法错误工作:
listOfPossibleParams.entrySet()
.stream()
.filter(p -> p.getValue() instanceof String)
.removeIf(e -> StringUtils.isBlank((String)e.getValue()));
If you can modify the Map in place, then you could do:如果您可以就地修改地图,那么您可以执行以下操作:
listOfPossibleParams.values()
.removeIf(v -> v instanceof String && StringUtils.isBlank((String) v));
If you want to build a new Map instead, you could have:如果你想建立一个新的地图,你可以:
listOfPossibleParams.entrySet()
.stream()
.filter(p -> {
Object v = p.getValue();
return !(v instanceof String) || !StringUtils.isBlank((String) v);
})
.collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.