Primitive Streams (IntStream)

Streams · lesson 11 of 42 · 4 min read

Work with numbers without boxing, using IntStream, LongStream and DoubleStream.

Open this lesson in the learning hub

Key points

  • IntStream, LongStream and DoubleStream carry raw primitives, so there is no wrapper object per element.
  • Go down with mapToInt, mapToLong, mapToDouble. Come back up with boxed() or mapToObj.
  • They add numeric terminal ops you do not get elsewhere: sum(), average(), max(), summaryStatistics().
  • range(a, b) excludes b. rangeClosed(a, b) includes it. Off-by-one bugs live right here.
  • average() returns an OptionalDouble, because an empty stream has no average, while sum() just returns 0.

Example

import java.util.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        System.out.println("range       : " + IntStream.range(1, 5).boxed().toList());
        System.out.println("rangeClosed : " + IntStream.rangeClosed(1, 5).boxed().toList());
        System.out.println("sum 1..100  : " + IntStream.rangeClosed(1, 100).sum());

        List<String> words = List.of("stream", "map", "collect");

        // Object stream -> primitive stream. No Integer boxing from here on.
        int letters = words.stream().mapToInt(String::length).sum();
        OptionalDouble avg = words.stream().mapToInt(String::length).average();

        // Primitive stream -> object stream.
        String bars = IntStream.rangeClosed(1, 4).mapToObj("*"::repeat).collect(Collectors.joining(" "));

        System.out.println("letters     : " + letters);
        System.out.println("average     : " + avg.getAsDouble());
        System.out.println("bars        : " + bars);
        System.out.println("stats       : " + IntStream.of(4, 8, 15, 16).summaryStatistics());
        System.out.println("no average  : " + IntStream.empty().average().isPresent());
    }
}

Numbers belong in an IntStream. Boxing a million Integers is pure waste.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Streams course, and every lesson in it is listed on the Streams contents page.