ExampleDifficulty: Intermediate1 min

The Same Three Steps Over Lines Read From a File

The same filter, the same map, the same collect — over a source that is not a collection, is not in memory, and may be larger than memory.

java
try (Stream<String> lines = Files.lines(path)) {
    List<String> refs = lines
            .filter(line -> !line.isBlank())
            .map(line -> line.split(",")[0])
            .toList();
}

There is no list here at all. Files.lines produces a stream over a file that is read as the pipeline pulls from it, which is why a file of ten million lines does not need ten million lines of memory.

Put this beside the list version and the shared fact comes out: neither source was touched until the terminal operation ran, and neither stream can be run a second time. A stream is a description of work over a source, and the source can be anything that can produce elements one at a time.