Modern Java 8+ Features · The Stream API
Boil a stream down to one value: a total with reduce, a count, the biggest value, and an average.
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);
}
}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].sum now points to a different Integer: 13000. s now points to a different Integer: 8000.total.s now points to a different Integer: 9000.s now points to a different Integer: 8000.lambda$main$1() has finished, so its variables are gone.busyDays.s now points to a different Integer: 9000.s now points to a different Integer: 8000.lambda$main$2() has finished, so its variables are gone.best.s now points to a different Integer: 9000.s now points to a different Integer: 8000.lambda$main$3() has finished, so its variables are gone.average.21000 2 9000 7000.0.