9706437
9706437

Reputation: 13

How to properly do nested iteration w/ Java 8 features such as stream, forEach etc?

What is the elegant way to rewrite something like this

private boolean containsNulls(HashBasedTable table) {
    for(Object column : table.columnKeySet()) {
        for(Object row : table.rowKeySet()) {
            if(table.get(row, column) == null) {
                return true;
            }
        }
    }
    return false;
}

using Java 8 features?

I am looking for something like

tableCells.stream().filter(cell -> cell.getValue() == null)
       .findFirst().orElse(null);

(per Return from lambda forEach() in java) however having some trouble writing it as a nested loop.

Suggestions?

Upvotes: 0

Views: 97

Answers (2)

yelliver
yelliver

Reputation: 5926

you can you 2 nested anyMatch():

private boolean containsNulls(HashBasedTable table) {
    return table.columnKeySet()
        .stream()
        .anyMatch(column -> table.rowKeySet()
            .stream()
            .anyMatch(row -> table.get(row, column) == null)
        );
}

Upvotes: 2

Eugene
Eugene

Reputation: 120858

 return table.columnKeySet()
             .stream()
             .flatMap(x -> table.rowKeySet().stream().map(y -> new Object[]{x,y}))
             .anyMatch(x -> table.get(x[1], x[0]) == null)

I did not compile this, so I hope did not miss a parentheses...

Just notice that you need the most recent java-8 there is to get this truly to be like your loop, read this for details.

Upvotes: 1

Related Questions