Abhishek Iyer
Abhishek Iyer

Reputation: 614

How to use streams to get a running count?

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

Answers (3)

Don Bottstein
Don Bottstein

Reputation: 1660

Alternative:

int sum = people.stream().mapToInt( p -> p.getChildren().orElse(0) ).sum();

Upvotes: 7

Alexis C.
Alexis C.

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

Jack
Jack

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

Related Questions