Numeric streams

IntStream, LongStream and DoubleStream are streams of primitives: no boxing per element, and the arithmetic terminal operations that a stream of Integer objects does not have. The three are the same shape, and this lesson uses the int one, which is the one a program reaches for.

IntStream.range and the terminal operations

range(from, to) stops before to and rangeClosed(from, to) includes it, which is the difference between the ten and the fifteen below:

import java.util.stream.IntStream; public class Ranges { public static void main(String[] args) { System.out.println(IntStream.range(1, 5).sum()); System.out.println(IntStream.rangeClosed(1, 5).sum()); System.out.println(IntStream.range(1, 5).count()); System.out.println(IntStream.range(1, 5).max().orElse(-1)); System.out.println(IntStream.range(1, 5).average().orElse(-1)); IntStream.range(1, 4).forEach(n -> System.out.print(n + " ")); System.out.println(); System.out.println(IntStream.iterate(1, n -> n * 2).limit(5).boxed().toList()); System.out.println(IntStream.rangeClosed(1, 5).map(n -> n * n).sum()); } }

javac -Xlint:all Ranges.java
java Ranges

10
15
4
4
2.5
1 2 3
[1, 2, 4, 8, 16]
55

The range holds 1, 2, 3 and 4, so the sum is ten and the count four. The average is 2.5 and it is an OptionalDouble, since an empty stream has no average, which is why orElse follows it. iterate is infinite and limit cuts it, and map on a numeric stream takes an IntUnaryOperator and answers another int stream, so the last line sums the squares 1, 4, 9, 16 and 25.

summaryStatistics

One pass over a numeric stream can produce all five numbers at once, and that is what summaryStatistics returns. The object can also take more values afterwards:

import java.util.IntSummaryStatistics; import java.util.List; import java.util.stream.Collectors; public class Stats { public static void main(String[] args) { List<Integer> scores = List.of(72, 88, 91, 65, 88); IntSummaryStatistics stats = scores.stream().mapToInt(Integer::intValue).summaryStatistics(); System.out.println("count " + stats.getCount()); System.out.println("sum " + stats.getSum()); System.out.println("min " + stats.getMin()); System.out.println("max " + stats.getMax()); System.out.printf("average %.3f%n", stats.getAverage()); stats.accept(100); System.out.println("after accept: " + stats.getCount() + " " + stats.getMax()); System.out.println(scores.stream().mapToInt(Integer::intValue).boxed().collect(Collectors.toList())); System.out.println(scores.stream().mapToInt(Integer::intValue).asLongStream().sum()); } }

javac -Xlint:all Stats.java
java Stats

count 5
sum 404
min 65
max 91
average 80.800
after accept: 6 100
[72, 88, 91, 65, 88]
404

The five numbers come from one traversal: 72 + 88 + 91 + 65 + 88 is 404, and divided by five is 80.8. The accept adds the sixth score and updates the count, the maximum and the average, which is what makes the object useful in a loop that reads values from somewhere else.

boxed and mapToInt

mapToInt goes from an object stream to a numeric one and boxed goes back. Both are explicit because the trip costs something: each int becomes an Integer object when it is boxed, and the collectors work on objects.

The rule that follows: stay on the numeric stream while the work is arithmetic, and box only at the end, when a list of objects is the result. asLongStream is the third direction, for a sum that may exceed the range of an int.

An empty numeric stream

An empty stream has a sum of zero, a count of zero and a min, a max and an average that are empty. The two that throw rather than answer are getAsInt on the empty OptionalInt and getAsDouble on the empty OptionalDouble, which is the next lesson from the other side.

summaryStatistics answers all five without an exception on an empty stream: count zero, sum zero, and zero for the minimum and the maximum, which is a value that a report has to special-case. That is the one place where the object hides an absence, and the documentation says so.

Exercises

  1. Print the sum of the even numbers from 1 to 20 with a numeric stream.
  2. Use summaryStatistics on the numbers 1 to 100 and print the average.
  3. Build a list of the first ten squares with rangeClosed, map and boxed.
  4. Print the count and the average of an empty IntStream.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does IntStream.range(1, 4) contain?

    Answer

    1, 2 and 3, because the upper bound is excluded

    range stops before the second argument, and rangeClosed includes it.

  2. Why does average() answer an OptionalDouble?

    Answer

    An empty stream has no average to answer

    There is no value to divide for zero elements, so the result is optional.

  3. What does summaryStatistics answer in one pass?

    Answer

    Count, sum, min, max and average

    The object accumulates the five numbers together, and also the median is not one of them.

  4. What does this program print? import java.util.stream.IntStream; public class Q1 { public static void main(String[] args) { System.out.println(IntStream.rangeClosed(1, 3).sum()); System.out.println(IntStream.range(1, 3).sum()); } }

    Answer

    6 / 3

    The closed range adds three values and the open one adds two.

  5. What does this program print? import java.util.stream.IntStream; public class Q2 { public static void main(String[] args) { System.out.println(IntStream.rangeClosed(1, 4).count()); System.out.println(IntStream.rangeClosed(1, 4).max().orElse(-1)); } }

    Answer

    4 / 4

    The closed range has four values, and the greatest is four.

  6. What does this program print? import java.util.List; import java.util.stream.Collectors; public class Q3 { public static void main(String[] args) { List<Integer> numbers = List.of(1, 2, 3); List<String> text = numbers.stream() .mapToInt(Integer::intValue) .map(n -> n * 10) .boxed() .map(String::valueOf) .collect(Collectors.toList()); System.out.println(text); } }

    Answer

    [10, 20, 30]

    Each number is multiplied by ten, boxed and turned into text.

  7. What does this program print? import java.util.IntSummaryStatistics; import java.util.stream.IntStream; public class Q4 { public static void main(String[] args) { IntSummaryStatistics stats = IntStream.rangeClosed(1, 4).summaryStatistics(); System.out.println(stats.getSum()); System.out.printf("%.1f%n", stats.getAverage()); } }

    Answer

    10 / 2.5

    The four numbers sum to ten and their average is 2.5.

  8. What does this program print? import java.util.stream.IntStream; public class Q5 { public static void main(String[] args) { System.out.println(IntStream.empty().sum()); System.out.println(IntStream.empty().average().isEmpty()); } }

    Answer

    0 / true

    The sum of nothing is zero, and the average is an empty OptionalDouble.

  9. Why is mapToInt needed before summaryStatistics?

    Answer

    The statistics work on a numeric stream, not on a stream of Integer objects

    The method belongs to IntStream, so the object stream has to be converted first.

  10. What does limit do to an infinite stream?

    Answer

    Cuts it after the given number of elements

    The pipeline becomes finite, which is what allows a terminal operation to finish.

The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.

Article author: Arthur Isaev