TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท java ยท streams ยท functional ยท collections

Java Streams

A lazy pipeline over a source of elements. Intermediate operations such as filter and map describe the work, and a single terminal operation such as collect or findFirst runs it, passing elements through one at a time.

14 min5 animations

๐Ÿ“š Builds on๐Ÿท๏ธ Generics and type erasure

๐Ÿ–จ๏ธ Cheat sheet

A conveyor belt with stations

Picture a cookie factory. A tray of freshly baked cookies sits at the start of a long conveyor belt. Along the belt are stations, each with one small job.

The sorting station looks at each cookie and only lets the whole ones through. The broken ones never go further. The icing station paints every cookie that reaches it. At the very end stands a packer, who puts what arrives into a box.

The belt doesn't keep any cookies. It only carries them from the tray, past the stations, to the packer. And the tray is never emptied: the belt works on a copy of each cookie, so when the run is over the tray still holds every cookie it started with.

There are two kinds of helper on this belt: the stations in the middle, which change or sort what passes, and the one person at the end, who decides what you get back: a box, a count, or just one cookie.

Source, intermediate operations, terminal operation

A java.util.stream.Stream<T> (a generic type, see Java generics) is a pipeline with three parts:

PartWhat it doesExamples
SourceSupplies the elementslist.stream(), Stream.of(a, b), Arrays.stream(arr), IntStream.range(0, 10)
Intermediate operationsReturn a new stream; describe workfilter, map, flatMap, sorted, distinct, limit
Terminal operationRuns the pipeline and produces a result or side effectcollect, toList, forEach, reduce, count, findFirst, anyMatch
1record Cookie(String flavour, boolean broken, int grams) {}2 3List<String> box = cookies.stream()        // source4    .filter(c -> !c.broken())             // intermediate5    .map(c -> "iced " + c.flavour())      // intermediate6    .toList();                            // terminal

A stream stores nothing and doesn't modify its source: cookies is the same list afterwards. A few intermediate operations are worth knowing apart:

  • map turns each element into exactly one new element; flatMap turns each into a stream of zero or more and flattens them, as in orders.stream().flatMap(o -> o.lines().stream()).
  • sorted and distinct are stateful: sorted must see every element before it can emit the first, and distinct remembers what it has already seen.
  • limit(n) is short-circuiting: it can finish a pipeline without reading the whole source, which is what makes Stream.iterate(1, n -> n * 2).limit(10) safe on an infinite source.
One belt, three kinds of part4 steps
Cookie box0123๐ŸชCookie tray๐Ÿ”Sorting station๐Ÿ–Œ๏ธIcing station๐Ÿง‘โ€๐ŸณPacker
Press play and watch it happen!

Nothing moves until someone asks

Here's the surprising part. Setting up the stations doesn't move a single cookie. The belt sits still until someone at the end asks for something. Factories call this being lazy, and it's a good thing: no work is done that nobody wants.

When the taster at the end says "I'd like one iced cookie", the belt starts. Each cookie travels the whole way, through every station, before the next one leaves the tray. The first cookie is broken, so the sorting station stops it. The second is whole, gets iced, and reaches the taster.

The taster has what they asked for, so the belt stops at once. The other cookies never leave the tray.

A belt run only happens once. When it's over, the stations are cleared away. If you want more cookies, you set up a new belt.

Laziness, one element at a time, single use

Intermediate operations are lazy: calling filter or map only adds a stage to the pipeline. Nothing is read from the source until a terminal operation is invoked.

Elements then flow one at a time through the whole chain (vertically), not stage by stage over the whole collection; only some stateful operations, such as sorted, act as a barrier. With a short-circuiting terminal operation (findFirst, findAny, anyMatch, allMatch, noneMatch) or limit, traversal stops as soon as the result is known:

1Optional<String> first = cookies.stream()2    .filter(c -> !c.broken())3    .map(c -> "iced " + c.flavour())4    .findFirst();       // reads cookies only until the first whole one

findFirst returns an Optional, because the stream might have no matching element. Use orElse, orElseThrow or ifPresent rather than calling get() blindly. (findFirst throws NullPointerException if the element it picks is null.)

A stream can be traversed only once. Calling a second terminal operation on the same stream throws IllegalStateException: stream has already been operated upon or closed. Keep the source, or a Supplier<Stream<T>>, and create a new stream each time.

Lazy, one at a time, and stops early6 steps
๐ŸชCookie tray๐Ÿ”Sorting station๐Ÿ–Œ๏ธIcing station
Press play and watch it happen!

Packing at the end of the belt

The person at the end can pack cookies in different ways, and each way is a packing rule. Put everything in one box. Sort them into bins by flavour. Write all the flavours on one long label, with commas between them. Or put them on a shelf with one named slot per flavour.

The shelf has a catch. Each slot holds one thing. If a second jam cookie arrives and the slot is already taken, the packer doesn't know what to do and stops the whole belt. So you give them a rule up front: "if a slot is taken, add the new one to the count".

Terminal operations and collectors

collect takes a Collector, a recipe for building a result. The Collectors class has the common ones:

1List<Cookie> all          = cookies.stream().collect(Collectors.toList());2Map<String, List<Cookie>> byFlavour =3                            cookies.stream().collect(Collectors.groupingBy(Cookie::flavour));4String label              = cookies.stream().map(Cookie::flavour).collect(Collectors.joining(", "));5Map<String, Integer> counts =6    cookies.stream().collect(Collectors.toMap(Cookie::flavour, c -> 1, Integer::sum));

toMap without a merge function throws IllegalStateException (Duplicate key jam ...) as soon as two elements map to the same key. The third argument says how to combine the values; groupingBy(Cookie::flavour, Collectors.counting()) does the same count more directly.

Other terminal operations: count(), reduce(0, Integer::sum), forEach(...), min/max (an Optional), and the matchers. reduce needs an associative function and a true identity value to give correct results in parallel.

Stream.toList() vs Collectors.toList(). Stream.toList() (Java 16) returns an unmodifiable list: add throws UnsupportedOperationException. It accepts null elements. Collectors.toList() makes no guarantee about the list's type or mutability (today it's an ArrayList), and Collectors.toUnmodifiableList() (Java 10) rejects nulls. If you need to modify the result, ask for it explicitly with Collectors.toCollection(ArrayList::new).

๐Ÿ”ง Going deeper

Custom intermediate operations: gatherers

Since Java 24 (JEP 485, after previews in 22 and 23), Stream::gather takes a Gatherer, a custom intermediate operation that can keep state, emit any number of elements per input and stop early. java.util.stream.Gatherers has ready-made ones:

1List<List<Integer>> packs = Stream.of(1, 2, 3, 4, 5)2    .gather(Gatherers.windowFixed(2))3    .toList();                             // [[1, 2], [3, 4], [5]]

Others include windowSliding, fold, scan and mapConcurrent (which runs a function on virtual threads with a concurrency limit). On older Java, the same jobs need a custom collector or a loop.

Packing rules and the duplicate key4 steps
๐ŸชBelt๐Ÿง‘โ€๐ŸณPacker๐Ÿ“ Jam slot๐ŸŒพ Oat slot
Press play and watch it happen!

A belt just for numbers

Sometimes you only care about numbers: how heavy is each cookie, and what do they weigh in total? On the ordinary belt, every weight card has to be put in its own little box before it can ride, and unpacked again at the end. That's a lot of boxes for a few numbers. This wrapping is called boxing.

So the factory has a special number belt. Weight cards ride on it bare, with no box, and the person at the end has buttons for "add them all up" and "what's the average". If the tray is empty, the average button honestly says "there's no average", instead of making one up.

Primitive streams and boxing

Stream<T> holds objects, so a Stream<Integer> boxes each int into an Integer and unboxes it again for arithmetic. IntStream, LongStream and DoubleStream hold primitives directly and add numeric terminal operations:

1int total = cookies.stream().mapToInt(Cookie::grams).sum();          // no boxing2OptionalDouble avg = cookies.stream().mapToInt(Cookie::grams).average();3IntSummaryStatistics stats = cookies.stream().mapToInt(Cookie::grams).summaryStatistics();4 5IntStream.range(0, 5);          // 0..46IntStream.rangeClosed(1, 5);    // 1..5

mapToInt, mapToLong and mapToDouble switch to a primitive stream; boxed() and mapToObj switch back. average(), max() and min() return OptionalDouble or OptionalInt, empty when there are no elements, while sum() of nothing is 0. Boxing costs an allocation per element (small Integer values are cached), which matters in hot loops over large data.

Boxed numbers and the number belt4 steps
๐ŸชCookie tray๐Ÿ“ฆOrdinary belt๐Ÿง‘โ€๐ŸณUnpacker๐Ÿ”ขNumber belt๐ŸงฎAdder with buttons
Press play and watch it happen!

More belts, one shared crew

To go faster, you can split the cookies across several workers at once. But those workers come from the factory's one shared crew, the same people every other team borrows. If your job keeps them busy waiting around, everyone else waits too.

Splitting has other costs. The workers finish in any order, so the cookies come out mixed up unless the packer is told to put them back in order. Splitting and rejoining takes effort, so for a handful of cookies one worker is quicker.

And stations must keep their hands to themselves. A station that also scribbles on a notepad on the wall is a problem: when two workers scribble on it at once, the notes get smudged and some are lost. Let the packer collect the results instead.

Side effects and parallel streams

Functions passed to stream operations should be non-interfering (don't modify the source) and preferably stateless with no side effects. This is the classic bug:

1List<String> names = new ArrayList<>();2cookies.parallelStream().map(Cookie::flavour).forEach(names::add);   // data race: lost elements or exceptions3 4List<String> safeNames = cookies.parallelStream().map(Cookie::flavour).toList();  // correct

Don't rely on side effects in peek or map happening at all: an implementation may skip stages that can't affect the result. For example, since Java 9 list.stream().peek(System.out::println).count() prints nothing, because the size is known from the source.

parallelStream() or .parallel() splits the source with its Spliterator and runs the chunks on ForkJoinPool.commonPool(), with the calling thread helping. That pool is shared by the whole JVM, including other parallel streams and CompletableFuture async methods without an executor, and its default parallelism is the number of processors minus one. When parallel streams hurt:

  • Blocking work (I/O, database calls) inside the pipeline ties up common-pool threads and starves everyone else.
  • Ordering: forEach gives no order guarantee in parallel; forEachOrdered and collect respect encounter order, at a cost. findAny and .unordered() let the stream skip that work.
  • Small or cheap data: splitting and merging outweighs the gain. Sources that split well (ArrayList, arrays, IntStream.range) help; LinkedList and Stream.iterate split poorly.

Measure before you switch. For blocking calls, use an explicit executor or virtual threads instead.

Parallel streams and the shared crew4 steps
๐Ÿ‘ฅ Shared crew๐ŸชCookie tray๐Ÿ‘ทCrew member 1๐Ÿ‘ทCrew member 2๐Ÿ“ Wall notepad๐Ÿง‘โ€๐ŸณPacker๐Ÿ™‹Another team
Press play and watch it happen!

๐Ÿงฉ Quick quiz

Quick quiz! 5 questions about Java Streams, told the same way as the story.
  1. The sorting and icing stations are set up, but nobody is at the end of the belt. How many cookies have been iced?
  2. The taster asks for one iced cookie. The first cookie is broken, the second is whole. What happens to the third cookie?
  3. The packer puts cookies on a shelf with one slot per flavour, with no rule for taken slots. Two jam cookies arrive. What happens?
  4. Two crew members both scribble results on the wall notepad at the same time. What's the better way?
  5. Your job has the crew phoning a slow supplier for every cookie. Why does that hurt other teams?
Answer every question to check.Passing marks Java Streams as done.
Got the hang of Java Streams? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

โš™๏ธ Java under the hoodStep 2 of 5

โ† Previous on the path๐Ÿท๏ธ Generics and type erasureNext on the path โ†’๐Ÿงน Garbage collection