Why Streams Exist

Streams · lesson 1 of 42 · 3 min read

When a stream beats a for loop, and what a stream actually is.

Open this lesson in the learning hub

Key points

  • A loop says how to walk a collection. A stream says what you want back.
  • Less bookkeeping: no index, no temporary list, no separate sorting step.
  • Streams do not store data. A stream is a recipe that runs over a source.
  • Each step is one line, so the intent survives your next code review.
  • Keep the loop when you mutate the source, need an index, or juggle several counters at once.

Example

import java.util.*;

public class Main {
    public static void main(String[] args) {
        List<String> names = List.of("ada", "grace", "alan", "barbara", "edsger");

        // Old way: make a bucket, walk the list, mutate the bucket.
        List<String> loopResult = new ArrayList<>();
        for (String n : names) {
            if (n.length() > 4) {
                loopResult.add(n.toUpperCase());
            }
        }
        Collections.sort(loopResult);

        // Stream way: say WHAT you want. The library does the walking.
        List<String> streamResult = names.stream()
                .filter(n -> n.length() > 4)
                .map(String::toUpperCase)
                .sorted()
                .toList();

        System.out.println("loop   : " + loopResult);
        System.out.println("stream : " + streamResult);
        System.out.println("same?  : " + loopResult.equals(streamResult));
    }
}

A stream is a recipe over data, not a second copy of it.

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.