Hey StackExchange
Hey StackExchange

Reputation: 2125

Java 8: iterating across some Map elements

I'm having a validate method that return a boolean.

I'm invoking this method (Java 7) as follow:

    boolean isValid = true;
    for (String key: aMap.keySet()) {
        isValid &= validate(key, aMap.get(key));
        if(!isValid) {
            break;
        }
    }

I would like to rewrite this code in Java 8.

Java 8 allows iterating across a Map using:

aMap.forEach((k,v) -> validate(k, v));

But this won't work:

aMap.forEach((k,v) -> isValid &= validate(k, v)); 

Question

How can I rewrite the the Java 7 code into Java 8 to achieve the same result?

Note

Raised a similar question here (but this time, for the iteration to continue through all the Map elements)

Upvotes: 1

Views: 91

Answers (1)

Eugene
Eugene

Reputation: 120858

boolean isValid = aMap.keySet()
                .stream()
                .allMatch(key -> validate(key, paramRow.getRowMap().get(colName))

As a side note, what does paramRow.getRowMap().get(colName) do? And where do you get colName? May be you don't have to recompute this for every single key

Upvotes: 3

Related Questions