Number streams in Java
IntStream does the math without the boxing.
import java.util.stream.IntStream;
// summaryStatistics answers four questions in one pass
var stats = IntStream.of(3, 8, 2, 9, 4).summaryStatistics();
System.out.println("sum " + stats.getSum());
System.out.println("avg " + stats.getAverage());
System.out.println("max " + stats.getMax());
// reduce folds left to right through an accumulator
var product = IntStream.rangeClosed(1, 5).reduce(1, (a, b) -> a * b);
System.out.println("5! = " + product);
System.out.println(IntStream.range(0, 5).boxed().toList());
How it works
summaryStatisticsanswers sum, average and max in one pass.reduceis the general fold: a seed, then combine left to right.boxedcrosses back to objects when a List is the goal.
Keywords and builtins used here
var
The run, in numbers
- Lines
- 13
- Characters to type
- 515
- Tokens
- 143
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 95 seconds.
Step 3 of 3 in Streams, step 24 of 29 in Language basics.