Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I count the number of elements that match a predicate with Streams?

Tags:

java

java-8

In Java7 I have this code:

public int getPlayersOnline() {
    int count = 0;
    for (Player player : players) {
        if (player.isActive()) {
            count++;
        }
    }
    return count;
}

I'm trying to use Java 8 features as much as possible, how can I go about improving this with lambdas?

like image 334
ImTomRS Avatar asked Oct 14 '15 22:10

ImTomRS


People also ask

How do I count a stream in Java?

Stream count() method in Java with exampleslong count() returns the count of elements in the stream. This is a special case of a reduction (A reduction operation takes a sequence of input elements and combines them into a single summary result by repeated application of a combining operation).


1 Answers

This would be a one-liner:

return (int) players.stream().filter(Player::isActive).count();
like image 85
Louis Wasserman Avatar answered Oct 11 '22 00:10

Louis Wasserman