Modern Java 8+ Features · The Stream API

Streams: reduce, count, max, average

Boil a stream down to one value: a total with reduce, a count, the biggest value, and an average.

StreamReduceDemo.java

import java.util.List;

public class StreamReduceDemo {
    public static void main(String[] args) {
        List<Integer> steps = List.of(4000, 9000, 8000);

        int total = steps.stream().reduce(0, (sum, s) -> sum + s);
        long busyDays = steps.stream().filter(s -> s > 5000).count();
        int best = steps.stream().mapToInt(s -> s).max().getAsInt();
        double average = steps.stream().mapToInt(s -> s).average().orElse(0);

        System.out.println(total + " " + busyDays + " " + best + " " + average);
    }
}

Step by step

  1. The program starts in main. args holds its command-line arguments (none here). steps is created on the stack and points to a new ImmutableCollections$ListN on the heap: [4000, 9000, 8000].
  2. reduce(0, …) starts with 0 and combines it with each value in turn.
  3. sum = 0 + 4000.
  4. sum now points to a different Integer: 13000. s now points to a different Integer: 8000.
  5. sum = 13000 + 8000 = 21000.
  6. The value it returned, 21000, is stored in total.
  7. filter, then count how many are left.
  8. s now points to a different Integer: 9000.
  9. s now points to a different Integer: 8000.
  10. lambda$main$1() has finished, so its variables are gone.
  11. The value it returned, 2, is stored in busyDays.
  12. mapToInt makes an IntStream, which has max().
  13. s now points to a different Integer: 9000.
  14. s now points to a different Integer: 8000.
  15. lambda$main$2() has finished, so its variables are gone.
  16. The value it returned, 9000, is stored in best.
  17. average() returns an OptionalDouble; orElse(0) gives 0 if the stream were empty.
  18. s now points to a different Integer: 9000.
  19. s now points to a different Integer: 8000.
  20. lambda$main$3() has finished, so its variables are gone.
  21. The value it returned, 7000, is stored in average.
  22. It prints 21000 2 9000 7000.0.
  23. 21000 steps, 2 busy days, best 9000, average 7000.0.