Skip to content
Tutorials Center
My learning

Topics

Lesson 101 of 201 ยท Generics and Functional Programming

Streams

Learn Java streams - creating them, filter/map/sorted/distinct/limit/skip, terminal operations, laziness, short-circuiting and IntStream ranges, with runnable examples.

Most code that works with collections follows the same recipe: take some elements, throw away the ones you don't want, transform the rest, and produce a result such as a list, a count or a total. With loops you write that recipe by hand every time, mixing what you want with how to iterate. A stream (Java 8, java.util.stream) lets you describe the recipe as a pipeline of steps, and the library does the iterating:

Java
List<String> shortNames = names.stream()
    .filter(name -> name.length() <= 4)
    .map(String::toUpperCase)
    .sorted()
    .toList();

You read it top to bottom: "from the names, keep the short ones, upper-case them, sort them, collect a list." This lesson covers how streams are built, the most important intermediate and terminal operations, the laziness that makes streams efficient, the primitive streams IntStream, LongStream and DoubleStream, and the mistakes that trip up newcomers. You'll use lambdas and method references everywhere, so make sure those feel familiar.

What a stream is (and isn't)

A stream is not a collection. It doesn't store elements; it's a one-time view that pulls elements from a source (a list, an array, a range of numbers, lines of text) and pushes them through a series of operations. Every pipeline has three parts:

  1. A source: list.stream(), Arrays.stream(array), Stream.of(...), IntStream.range(0, 10), text.lines().
  2. Zero or more intermediate operations: filter, map, sorted, distinct, limit, ... Each returns a new stream, so you can chain them.
  3. Exactly one terminal operation: toList, count, forEach, sum, anyMatch, findFirst, ... It produces a result (or a side effect) and ends the stream.

Streams also never modify their source. filter doesn't remove anything from your list; it only decides what flows further down the pipeline.

Java Your first stream pipeline

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The same logic with a loop needs a temporary list, an if, an add and a separate Collections.sort call. The stream version says only what matters.

Creating streams

You'll mostly get streams from collections, but there are many sources:

Java
List.of(1, 2, 3).stream()           // any Collection
Stream.of("a", "b", "c")            // fixed values
Arrays.stream(new int[] {4, 5, 6})  // an array (int[] gives an IntStream)
IntStream.range(0, 5)               // 0, 1, 2, 3, 4
IntStream.rangeClosed(1, 5)         // 1, 2, 3, 4, 5
"one\ntwo\nthree".lines()           // Stream<String> of lines
"hello".chars()                     // IntStream of UTF-16 char values
map.entrySet().stream()             // Map entries (a Map itself has no stream())
Stream.empty()                      // no elements

Infinite sources like Stream.iterate and Stream.generate, and the difference between Stream.of(array) and Arrays.stream(array), are covered in Advanced Streams.

Intermediate operations

These are the everyday building blocks. All of them are lazy and return a new stream:

Operation What it does
filter(predicate) Keeps only elements for which the predicate returns true
map(function) Replaces each element with the function's result (types may change)
mapToInt / mapToLong / mapToDouble Like map, but produces a primitive stream
sorted() / sorted(comparator) Sorts by natural order or by a Comparator
distinct() Removes duplicates, using equals (keeps the first occurrence)
limit(n) Passes at most the first n elements
skip(n) Throws away the first n elements
peek(action) Runs an action on each element as it passes (for debugging)
Java filter, map, distinct, sorted, skip and limit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice how map changes the element type: the pipeline starts as Stream<Product> and becomes Stream<String> after .map(Product::name). Order matters too: skip(3).limit(3) gives elements 4โ€“6, while limit(3).skip(3) would give nothing.

Terminal operations

Nothing happens until you call a terminal operation. The common ones:

Operation Result
toList() (Java 16) An unmodifiable List
collect(collector) Anything a collector builds: maps, sets, joined strings, groups (next lesson)
forEach(action) Runs the action for each element; returns nothing
count() Number of elements, as a long
min(comparator) / max(comparator) An Optional with the smallest/largest element
findFirst() / findAny() An Optional with an element, if there is one
anyMatch / allMatch / noneMatch A boolean
reduce(...) Combines all elements into one value
sum(), average(), summaryStatistics() On primitive streams only
toArray() An array

Operations that might have no answer, like max on an empty stream, return an Optional instead of null. You unwrap it with methods such as orElse:

Java Terminal operations and Optional results

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

findFirst on an empty result prints Optional.empty rather than throwing. toList() gives an unmodifiable list; if you need to add to it later, collect with Collectors.toCollection(ArrayList::new) or wrap it: new ArrayList<>(stream.toList()).

Laziness: how a pipeline really runs

A pipeline doesn't run step by step over the whole collection ("filter everything, then map everything"). Instead, each element travels through all the stages before the next element starts, and nothing moves at all until a terminal operation asks for results. peek makes this visible:

Java Watching laziness and short-circuiting with peek

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The output shows two important facts:

  • Building a pipeline does no work. "Pipeline built" appears before any saw line.
  • Short-circuiting stops early. Because of limit(2), the stream stops as soon as two elements reach the end: dog and eel are never even looked at.

limit, findFirst, findAny, anyMatch, allMatch and noneMatch are short-circuiting. Thanks to them, a stream can safely search a huge (or even infinite) source and stop at the first match.

Some operations are stateful and need to see more than one element before passing anything on. sorted() must read every element before it can emit the smallest, and distinct() remembers what it has seen. Put cheap filter steps before sorted so it has less to sort.

Use peek only for debugging. Its action may be skipped when the stream can compute the result without visiting elements. For example, since Java 9, List.of(1, 2, 3).stream().peek(...).count() may print nothing, because the size is already known. Never put real work (like adding to a list) in peek or map.

Primitive streams: IntStream, LongStream, DoubleStream

A Stream<Integer> holds boxed Integer objects. For number crunching, Java has specialized streams of primitives that avoid boxing and add math operations: sum(), average(), min(), max() and summaryStatistics().

  • Get one with mapToInt, mapToLong, mapToDouble, or from IntStream.range, Arrays.stream(int[]) and String.chars().
  • Go back to objects with boxed() (gives Stream<Integer>) or mapToObj(...).
  • average() returns an OptionalDouble, because an empty stream has no average.
Java IntStream ranges and number crunching

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

IntStream.range(0, list.size()) is the standard way to get indexes in a stream, because streams themselves don't expose positions.

Common mistakes

Reusing a stream. A stream can be consumed only once. Calling a second terminal operation throws an exception:

Java
Stream<String> s = Stream.of("a", "b");
s.count();
s.toList();   // IllegalStateException: stream has already been operated upon or closed

Store the source (the list) in a variable, not the stream, and call stream() again when you need a new pipeline. If you need a pipeline you can rerun, wrap it in a Supplier<Stream<T>>.

Changing the source during the pipeline. Adding to or removing from the list you are streaming (inside forEach or filter) causes ConcurrentModificationException or unpredictable results. Collect a new list instead, or use list.removeIf(...).

Side effects instead of results. This works, but it's a loop in disguise and breaks if the stream ever becomes parallel:

Java
List<String> out = new ArrayList<>();
names.stream().filter(n -> n.startsWith("A")).forEach(out::add);   // avoid

List<String> out2 = names.stream().filter(n -> n.startsWith("A")).toList();   // prefer

Forgetting the terminal operation. A pipeline without one compiles but does nothing. list.stream().map(this::save); saves nothing.

Overusing streams. Streams shine for filter/transform/aggregate work. A plain for loop is often clearer when you need break with complex conditions, checked exceptions, several results at once, or to mutate local variables (lambdas can only capture effectively final variables). Choose the version that reads best.

Streams vs loops: a side-by-side

Here is the same task, "the average length of distinct words longer than three letters, ignoring case," both ways:

Java The same task with a loop and with a stream

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The loop mixes four concerns (splitting, normalizing, deduplicating, averaging) in one block with two mutable variables. The stream gives each concern its own line, and average().orElse(0) handles the empty case explicitly.

Streams are not automatically faster than loops. For small collections the difference is negligible either way; for hot code, measure. Their main win is clarity, plus easy access to powerful operations like grouping, which the next lesson covers.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? Stream.of("b", "a", "c").peek(IO::print).filter(s -> s.equals("a")).findFirst(); (the result is not printed)

    findFirst is short-circuiting. Elements flow one at a time, so peek sees b (rejected) and then a (a match), and the stream stops before c.
  2. 2. What does IntStream.range(1, 4).sum() return?

    range is end-exclusive, so it produces 1, 2 and 3, which sum to 6. rangeClosed(1, 4) would give 10.
  3. 3. You store a stream in a variable, call count() on it, then call toList() on the same variable. What happens?

    A stream can only be consumed once. The second terminal operation throws IllegalStateException; create a new stream from the source instead.
  4. 4. Which statement about names.stream().filter(n -> n.length() > 3).map(String::trim); with no terminal operation is true?

    Intermediate operations only describe the pipeline. Without a terminal operation no element is processed, and streams never modify their source anyway.
  5. 5. What does List.of(3, 1, 3, 2).stream().distinct().sorted().skip(1).toList() return?

    distinct gives 3, 1, 2; sorted gives 1, 2, 3; skip(1) drops the 1, leaving [2, 3].

Summary

  • A stream pipeline is a source, zero or more intermediate operations and one terminal operation. Streams don't store data and never change their source.
  • Key intermediate operations: filter, map, mapToInt, sorted, distinct, limit, skip, peek (debugging only).
  • Key terminal operations: toList (unmodifiable), collect, forEach, count, min/max, findFirst, anyMatch/allMatch/noneMatch, reduce.
  • Pipelines are lazy: nothing runs until the terminal operation, elements flow through all stages one at a time, and short-circuiting operations stop early.
  • IntStream, LongStream and DoubleStream avoid boxing and add sum, average and summaryStatistics; range is end-exclusive, rangeClosed is inclusive.
  • A stream can be used only once; avoid side effects and source modification, and prefer a loop when it's clearer.

Next: Collecting Stream Results, where you'll group, partition, join and summarize stream elements with collectors.