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?
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).
This would be a one-liner:
return (int) players.stream().filter(Player::isActive).count();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With