Java – how to calculate the number of elements that match the streams predicate?

In Java 7, I have this Code:

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

I use Java 8 features as much as I can. Can I use Lambdas to improve this?

Solution

This will be a single line:

return (int) players.stream().filter(Player::isActive).count();
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>