Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 589
cerbin Avatar asked Jul 13 '17 14:07

cerbin


People also ask

How to count the number of items in a stream?

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

How to count the matching items in the stream in Python?

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

How to count the number of matches in stream in Java?

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.

How many given strings in 2D character array [ ]?

2D String [ ] - { "LOAPYS", "KAYSOT", "LAYSST", "MLVAYS", "LAYSAA", "LAOYLS" }; Output- Count of number of given strings in 2D character array: 7


1 Answers

I believe this answer is slightly more expressive:

int freeSpaces = (int) Arrays.stream(board)
                             .map(CharBuffer::wrap)
                             .flatMapToInt(CharBuffer::chars)
                             .filter(i -> i == ' ')
                             .count();
like image 119
Jacob G. Avatar answered Sep 20 '22 17:09

Jacob G.