Skip to content

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

    Java / Modern Java

    Streams: The Idea

    A stream is a sequence of elements you process with a pipeline of operations. It does not store the elements — it describes a computation

    Chapter 4 of 112 min readOften asked in interviews

    The Plain Picture#

    A factory conveyor belt (the same picture as Unix pipes in The Linux Command Line Ch 5): items come from a source, pass through stations — a sieve, a painter, a sorter — and are packed into a box at the end. You describe the stations; the belt moves the items.

    The Real Names#

    • A stream is a sequence of elements you process with a pipeline of operations. It does not store the elements — it describes a computation over a source (a collection, an array, a range of numbers, lines of a file).

    • A pipeline has three parts:

    Output
       SOURCE                   INTERMEDIATE OPERATIONS                     TERMINAL OPERATION
       students.stream()   →    .filter(...)  .sorted(...)  .map(...)   →   .toList()
       (where items come from)  (each returns a new stream; LAZY)            (produces the result; triggers the work)
    • Intermediate operations (filter, map, sorted, distinct, limit, flatMap…) return another stream and do nothing until a terminal operation runs (Ch 7).

    • Terminal operations (toList, collect, count, sum, forEach, reduce, findFirst, anyMatch…) produce a result or side effect and close the stream.

    • Streams don't modify the source, and a stream can only be used once:

    Java
    Stream<String> once = Stream.of("x");
    
    once.count();
    
    once.count(); // IllegalStateException: stream has already been operated upon or closed
    • Style: declarative (say what you want) rather than imperative (say how, step by step, with loops and temporary lists).

    Check yourself

    3 questions
    1

    Name the three parts of a stream pipeline.

    Show answer

    Source, intermediate operations, terminal operation.

    2

    Does a stream store data? Does it change its source?

    Show answer

    No and no.

    3

    What happens if you call two terminal operations on the same stream?

    Show answer

    The second throws IllegalStateException — streams are single-use.