Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Modern Java

    Laziness, Primitive Streams and Parallel Streams

    Intermediate operations don't run until a terminal operation pulls elements through, and elements go through the pipeline one at a time, not

    Chapter 7 of 114 min read

    7.1 Laziness — watch it happen#

    Intermediate operations don't run until a terminal operation pulls elements through, and elements go through the pipeline one at a time, not stage by stage:

    Java
    Stream.of("a", "b", "c", "d")
        .filter(s -> {
            System.out.println("  filter " + s);
            return !s.equals("b");
        })
        .map(s -> {
            System.out.println("  map " + s);
            return s.toUpperCase();
        })
        .limit(2)
        .forEach(s -> System.out.println("  got " + s));
    Output
      filter a
      map a
      got A
      filter b          ← b fails the filter, so it never reaches map
      filter c
      map c
      got C             ← limit(2) is satisfied — "d" is never even looked at

    Consequences:

    • Elements flow vertically (a through every stage, then c), not horizontally.

    • Short-circuiting operations (limit, findFirst, anyMatch) stop early — work on "d" never happens. This lets streams even work on infinite sources: Stream.iterate(1, x -> x * 2).limit(10).

    • Without a terminal operation, nothing runs at all — a common "why didn't my code do anything?" bug.

    • sorted is the exception to one-at-a-time: it has to see all elements before passing any on.

    7.2 Primitive streams — avoid boxing#

    Stream<Integer> boxes every number (Classes, Objects and Memory Ch 8). IntStream, LongStream, DoubleStream work on primitives and add maths methods:

    Java
    students.stream().mapToInt(Student::score).sum()                 // 835
    students.stream().mapToInt(Student::score).average().getAsDouble()   // 167.0   (average returns OptionalDouble)
    students.stream().mapToInt(Student::score).max().getAsInt()       // 200
    IntStream.rangeClosed(1, 5).map(x -> x * x).boxed().toList()      // [1, 4, 9, 16, 25]    (boxed() → Stream<Integer>)
    IntStream.range(0, 5).sum()                                       // 10     (range excludes the end, rangeClosed includes it)
    int[] arr = {5, 3, 8};
    Arrays.stream(arr).max().getAsInt()                               // 8
    Arrays.stream(arr).boxed().sorted(Comparator.reverseOrder()).toList()   // [8, 5, 3]  — sorting an int[] descending needs boxing

    7.3 Parallel streams — powerful and easy to misuse#

    .parallel() (or collection.parallelStream()) splits the work across CPU cores (How Computers Work Ch 5) using a shared thread pool (Concurrency):

    Java
    LongStream.rangeClosed(1, 50_000_000).sum()                // sequential 64 ms
    LongStream.rangeClosed(1, 50_000_000).parallel().sum()     // parallel    8 ms    (8 cores on this Mac)

    When parallel streams help: large data (hundreds of thousands of elements or more), CPU-heavy work per element, sources that split cheaply (arrays, ArrayList, ranges), and operations with no shared state.

    When they hurt or break:

    • small collections — splitting and merging cost more than the work;

    • I/O inside the stream (network calls, database queries) — they block the shared pool's few threads, slowing every parallel stream in the application;

    • shared mutable state — parallelStream().forEach(x -> list.add(x)) on an ArrayList is a race condition (Operating Systems Ch 8) that silently loses elements or throws;

    • order-dependent operations (findFirst, limit, forEachOrdered) lose much of the speed-up.

    Default to sequential. Go parallel only after measuring.

    Check yourself

    3 questions
    1

    In the laziness example, why is "d" never printed?

    Show answer

    limit(2) was satisfied after "c", and streams are lazy and short-circuiting, so no more elements were pulled.

    2

    Why prefer mapToInt(...).sum() over map(...).reduce(0, Integer::sum)?

    Show answer

    It avoids boxing every number and is clearer.

    3

    Give two situations where .parallel() is a bad idea.

    Show answer

    Any two: small data; I/O or blocking calls inside; shared mutable state; order-dependent operations.