Java - Using the map() and reduce() methods to count the number of elements in a stream

Introduction

Map each element in the stream to 1 and compute the sum.

long personCount = Person.persons()
                         .stream()
                         .mapToLong(p -> 1L)
                         .sum();

The following code uses the map() and reduce() methods to implement the count operation:

long personCount = Person.persons()
                         .stream()
                         .map(p -> 1L)
                         .reduce(0L, Long::sum);

The following code uses only the reduce() method to implement the count operation:

long personCount = Person.persons()
                         .stream()
                         .reduce(0L, (partialCount, person) -> partialCount + 1L, Long::sum);

Related Topic