Reputation: 614
I have a class
class Person {
String name;
....
Optional<Integer> children;
}
How do I use streams to get a total count of all children?
public int totalCount(final Set<Person> people) {
int total = 0;
for (Person person : people) {
if (person.getChildren().isPresent()) {
total += person.getChildren().get();
}
}
return total;
}
How can I do this with Java 8 streams?
public int totalCount(final Set<Person> people) {
int total = 0;
people.stream()
.filter(p -> p.getChildren().isPresent())
// ???
}
Upvotes: 2
Views: 1331
Reputation: 1660
Alternative:
int sum = people.stream().mapToInt( p -> p.getChildren().orElse(0) ).sum();
Upvotes: 7
Reputation: 93842
Another variant would be to use mapToInt
in order to obtain an IntStream
and then call sum()
on it:
int count = people.stream()
.filter(p -> p.getChildren().isPresent())
.mapToInt(p -> p.getChildren().get())
.sum();
Upvotes: 2
Reputation: 133577
You can use Collectors.summingInt
:
int count = people.stream()
.filter(p -> p.getChilden().isPresent())
.collect(Collectors.summingInt(p -> p.getChildren().get()));
Upvotes: 3