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;
}
The count () method is a terminal operation. 1. Java Stream count () Method The Stream interface has a default method called count () that returns a long value indicating the number of items in the stream. 2. Java Stream count () Examples
Learn to count the matching items in the Stream that are passed by a specified filter expression. To count the items, we can use the following two methods and both are terminal operations and will give the same result. 1. Stream count () API 2. Counting Matches in Stream 1. Stream count () API
The Stream interface has a default method called count () that returns a long value indicating the number of matching items in the stream. To use the count () method, call it on any Stream instance. 2. Counting Matches in Stream In this example, we are counting the number of elements in different kinds of streams such as IntStream, LongStream.
2D String [ ] - { "LOAPYS", "KAYSOT", "LAYSST", "MLVAYS", "LAYSAA", "LAOYLS" }; Output- Count of number of given strings in 2D character array: 7
I believe this answer is slightly more expressive:
int freeSpaces = (int) Arrays.stream(board)
.map(CharBuffer::wrap)
.flatMapToInt(CharBuffer::chars)
.filter(i -> i == ' ')
.count();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With