typestar

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

  1. summaryStatistics answers sum, average and max in one pass.
  2. reduce is the general fold: a seed, then combine left to right.
  3. boxed crosses back to objects when a List is the goal.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 3 in Streams, step 24 of 29 in Language basics.

← Previous Next →