Counting specific characters in a two-dimensional array using stream

I would like to count the occurrences of a character (e.g. space:) ' ' in a 2D array using a stream. I tried to find a solution. Here is my code using nested loops:

public int countFreeSpaces() {
    int freeSpaces = 0;
    for (int i = 0; i < height; i++) {
        for (int j = 0; j < width; j++) {
            if (board[j][i] == ' ') freeSpaces++;
        }
    }
    return freeSpaces;
}
+6
source share
2 answers

I believe this answer is somewhat more expressive:

int freeSpaces = (int) Arrays.stream(board)
                             .map(CharBuffer::wrap)
                             .flatMapToInt(CharBuffer::chars)
                             .filter(i -> i == ' ')
                             .count();
+7
source

How about this?

//                      v--- create a Stream<char[]>             
int spaces = (int) Stream.of(board)
                          .flatMapToInt(cells->IntStream.range(0, cells.length)
                          .filter(i -> cells[i] == ' '))
                          .count();
+2
source

All Articles