The problem is that you are using count()
, which will return long
.
Please, try instead:
int count = words.stream()
.mapToInt(word -> "".equals(word) ? 1 : 0)
.sum()
;
Or:
int count = words.stream()
.map(word -> "".equals(word) ? 1 : 0)
.reduce(0, (a, b) -> a + b)
;
Very similar:
int count = words.stream()
.map(word -> "".equals(word) ? 1 : 0)
.reduce(0, Integer::sum)
;
Or using collectors:
int count = words.stream()
.map(word -> "".equals(word) ? 1 : 0)
.collect(Collectors.summingInt(Integer::intValue))
;
Or, much better, in one row, as suggested by @Holger:
int count = words.stream()
.collect(Collectors.summingInt(word -> "".equals(word) ? 1 : 0))
;
All these examples can be enclosed in a method, more general, like this:
import java.util.Objects;
//...
public int getCount(List<String> terms, String searchTerm) {
Objects.requireNonNull(terms, "Null terms list provided");
int count = terms.stream()
.mapToInt(word -> Objects.equals(searchTerm, word)? 1 : 0)
.sum();
;
return count;
}
In your use case:
int countOfEmptyString = getCount(words, "");
As a side note, to avoid npe issues and null
checking, always compare the information like this (""
will never be null
):
"".equals(element)
Instead of (element
can be null
):
element.equals("")
By the way, the @ETO answer is a very suitable alternative as well.