cerbin
cerbin

Reputation: 1189

Counting specific characters in two dimensional array using stream

I would like to count occurrences of a character (for example the space: ' ' ) in 2D Array, using stream. I was trying to find a solution. Here is my code, using a 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;
}

Upvotes: 8

Views: 1833

Answers (2)

holi-java
holi-java

Reputation: 30696

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();

Upvotes: 2

Jacob G.
Jacob G.

Reputation: 29730

I believe this answer is slightly more expressive:

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

Upvotes: 9

Related Questions