如何使用流来获取运行计数?

时间:2015-10-08 18:54:20

标签: java-8 java-stream

我有一个班级

class Person {
    String name;
    ....
    Optional<Integer> 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; 
}

如何使用Java 8流进行此操作?

public int totalCount(final Set<Person> people) {
    int total = 0;
    people.stream()
          .filter(p -> p.getChildren().isPresent())
          // ???
}

3 个答案:

答案 0 :(得分:6)

替代:

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

答案 1 :(得分:3)

您可以使用Collectors.summingInt

int count = people.stream()
      .filter(p -> p.getChilden().isPresent())
      .collect(Collectors.summingInt(p -> p.getChildren().get()));

答案 2 :(得分:2)

另一种变体是使用mapToInt来获取IntStream,然后在其上调用sum()

int count = people.stream()
                  .filter(p -> p.getChildren().isPresent())
                  .mapToInt(p -> p.getChildren().get())
                  .sum();