简体   繁体   English

Java 8 Streams - 基于条件的迭代器映射和删除

[英]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.

相关问题 使用Java 8 Streams基于常见条件从两个不同的列表创建映射 - Create a map from two different lists based on common conditions using Java 8 Streams java 流是否能够从映射/过滤条件中延迟减少? - Are java streams able to lazilly reduce from map/filter conditions? 如何使用java 8流通过耦合条件获取已排序的分页映射 - How to get sorted paged map by couple conditions using java 8 streams 根据 json 中的某些条件检索输出,使用 java 流列出 - Retrieving output based on certain conditions in json, list using java streams 删除列表中的重复项<map<string, object> &gt; 在 java 中使用流</map<string,> - Remove duplicates in List<Map<String, Object>> using Streams in java 基于密钥的 Map 过滤列表使用 Java 流 - Filter List of Map Based on Key Using Java Streams java - 如何根据带有Java流的键将地图的值分组到列表中? - How to group values of map into lists based on key with java streams? Java 8 Streams:根据不同的属性多次映射同一个对象 - Java 8 Streams: Map the same object multiple times based on different properties 如何使用 Java 8 个流根据 map 参数返回的列表进行过滤 - How to filter based on list returned by map param using Java 8 streams 使用Java 8流重构循环和条件 - Refactor loops and conditions with Java 8 streams
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM