Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This would be a one-liner:

return (int) players.stream().filter(Player::isActive).count();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...