Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()));
like image 736
Taobitz Avatar asked Nov 24 '15 09:11

Taobitz


1 Answers

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));
like image 51
Tunaki Avatar answered Oct 12 '22 12:10

Tunaki