Reputation: 1189
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
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
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