JAVA-230 · Lesson 3 of 12 · 21 min
The Stream API
▶ Video coming soon A video version of this lesson is on the way.
On Wednesday, September 29, Odile came to the back room with a printout. "Every month I copy the repair log into a spreadsheet to answer three questions," she said: how many repairs, which kinds, and how much shop time they took. Hamza's first answer was three loops, each with its own counter. Ingrid showed him a fourth way that read like Odile's questions: take the repairs, keep the ones from September, turn each into its minutes, add them up. That is a stream pipeline. The Stream API, in java.util.stream, lets you describe what to do with a sequence of values as a chain of steps, and it is where the lambdas and method references of the last two weeks pay off.
Source, intermediate operations, terminal operation
Every pipeline has three parts. A source produces the elements: most often a collection's stream() method, but also Stream.of(...), Arrays.stream(array), IntStream.range(a, b), the lines of a file (lesson 7) or the characters of a string. Zero or more intermediate operations each return a new stream: filter keeps elements that pass a test, map turns each element into something else, sorted puts them in order, distinct drops duplicates, limit and skip cut the sequence. Finally, one terminal operation produces a result or an effect: count, sum, toList, forEach, anyMatch, findFirst, reduce or collect.
import java.time.*;
import java.util.*;
public class Main {
enum Kind { FLAT, BRAKES, GEARS, WHEEL_TRUE, TUNE_UP }
record Repair(int ticket, LocalDate day, Kind kind, int minutes) { }
public static void main(String[] args) {
List<Repair> log = List.of(
new Repair(501, LocalDate.of(2027, 8, 31), Kind.TUNE_UP, 75),
new Repair(502, LocalDate.of(2027, 9, 2), Kind.FLAT, 20),
new Repair(503, LocalDate.of(2027, 9, 2), Kind.BRAKES, 45),
new Repair(504, LocalDate.of(2027, 9, 9), Kind.FLAT, 15),
new Repair(505, LocalDate.of(2027, 9, 16), Kind.GEARS, 60),
new Repair(506, LocalDate.of(2027, 9, 23), Kind.WHEEL_TRUE, 40),
new Repair(507, LocalDate.of(2027, 10, 1), Kind.FLAT, 20));
long septemberRepairs = log.stream()
.filter(r -> r.day().getMonth() == Month.SEPTEMBER)
.count();
int septemberMinutes = log.stream()
.filter(r -> r.day().getMonth() == Month.SEPTEMBER)
.mapToInt(Repair::minutes)
.sum();
List<Integer> flatTickets = log.stream()
.filter(r -> r.kind() == Kind.FLAT)
.map(Repair::ticket)
.toList();
System.out.println("September repairs: " + septemberRepairs);
System.out.println("September shop time: " + septemberMinutes + " minutes");
System.out.println("Flat tickets: " + flatTickets);
}
}September repairs: 5 September shop time: 180 minutes Flat tickets: [502, 504, 507]
What this code does
Each pipeline starts from log.stream(), keeps the repairs it wants with filter and finishes with one terminal operation. mapToInt turns the repairs into an IntStream of minutes so sum can add them without boxing, giving 180 minutes for the five September repairs. toList, added in Java 16, collects the flat-tire ticket numbers into an unmodifiable list.
The pipelines do not change log. A stream is not a collection: it holds no data of its own, it reads from its source, and it never modifies the source. That makes pipelines safe to write against shared lists, and it is why you collect the result into a new list rather than removing elements from the old one.
Laziness: nothing happens until the terminal operation
Intermediate operations are lazy. Calling filter or map only records the step; no element is touched until a terminal operation asks for results. Then the elements flow through the whole pipeline one at a time, rather than each step processing the whole list before the next begins. This lets operations such as findFirst, anyMatch and limit stop early, because once the answer is known no more elements are pulled from the source.
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> codes = List.of("BELL", "TUBE-700x25", "TUBE-26x2", "CHAIN-11");
var pipeline = codes.stream()
.filter(c -> { System.out.println(" filter " + c); return c.startsWith("TUBE"); })
.map(c -> { System.out.println(" map " + c); return c.toLowerCase(); });
System.out.println("Pipeline built, nothing has run yet.");
Optional<String> first = pipeline.findFirst();
System.out.println("First tube: " + first.orElse("none"));
}
}Pipeline built, nothing has run yet. filter BELL filter TUBE-700x25 map TUBE-700x25 First tube: tube-700x25
What this code does
Building the pipeline prints nothing, because filter and map only describe steps. When findFirst runs, BELL is tested and rejected, TUBE-700x25 passes the filter and is mapped, and the pipeline stops there. The last two codes are never read, which is laziness and short-circuiting working together.
Laziness has a practical consequence: printing inside map or filter is a poor way to debug, because what you see depends on the terminal operation. Use peek only for debugging, and never rely on it for real work; the library may skip it when it can work out the answer without visiting every element, as count sometimes does.
A stream can be used only once
A stream is a one-time pass over its source. After a terminal operation, the stream is used up, and calling another operation on it throws IllegalStateException. If you need two results, either create two streams from the source, or collect once into a list and stream that list again. Keeping a stream in a field or passing it between methods is almost always a mistake; pass the collection, or a Supplier<Stream<T>>, instead.
import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
List<Integer> minutes = List.of(20, 45, 15, 60);
Stream<Integer> s = minutes.stream();
System.out.println("Count: " + s.count());
System.out.println("Max: " + s.max(Integer::compare).get());
}
}What this code does
The first terminal operation, count, uses the stream up, so the call to max on the same stream throws an IllegalStateException with the message that the stream has already been operated upon or closed. The count is printed before the failure, which shows the program got that far. Writing minutes.stream() a second time fixes it, because each call creates a fresh stream from the list.
$ javac Main.java
$ java Main
Count: 4
Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed
at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:229)
at java.base/java.util.stream.ReferencePipeline.reduce(ReferencePipeline.java:662)
at java.base/java.util.stream.ReferencePipeline.max(ReferencePipeline.java:698)
at Main.main(Main.java:9)The operations you will use most
| Operation | Kind | What it does |
|---|---|---|
| filter(Predicate) | intermediate | keeps elements that pass the test |
| map(Function) | intermediate | turns each element into another value |
| mapToInt / mapToLong / mapToDouble | intermediate | turns elements into primitives, giving sum, average, max |
| flatMap(Function) | intermediate | turns each element into a stream and joins them |
| sorted() / sorted(Comparator) | intermediate | orders the elements (needs to see them all) |
| distinct() | intermediate | drops duplicates using equals |
| limit(n) / skip(n) | intermediate | keeps the first n / drops the first n |
| toList() | terminal | an unmodifiable list of the results |
| count() / sum() / average() | terminal | how many, the total, the mean |
| anyMatch / allMatch / noneMatch | terminal | a boolean answer, stopping early |
| findFirst() / min / max | terminal | an Optional result (lesson 5) |
| reduce(identity, BinaryOperator) | terminal | combines all elements into one value |
| collect(Collector) | terminal | builds a collection or summary (lesson 4) |
flatMap deserves a word. When each element holds several values, such as a booking with a list of parts used, map would give a stream of lists, but flatMap(b -> b.parts().stream()) gives one stream of all the parts. reduce combines elements with an operation and a starting value, such as reduce(0, Integer::sum); for sums and counts the specialized sum and count are clearer, so keep reduce for combinations that have no ready-made method.
import java.util.*;
import java.util.stream.*;
public class Main {
record Repair(int ticket, String bike, List<String> partsUsed, int minutes) { }
public static void main(String[] args) {
List<Repair> repairs = List.of(
new Repair(502, "CITY-2", List.of("TUBE-700x25"), 20),
new Repair(503, "CITY-4", List.of("PAD-ROAD", "PAD-ROAD", "CABLE-BRAKE"), 45),
new Repair(505, "CARGO-1", List.of("CHAIN-11"), 60),
new Repair(508, "CITY-2", List.of("TUBE-700x25", "BELL"), 25));
List<String> allParts = repairs.stream()
.flatMap(r -> r.partsUsed().stream())
.toList();
List<String> kinds = allParts.stream().distinct().sorted().toList();
int longest = repairs.stream().mapToInt(Repair::minutes).max().orElse(0);
double average = repairs.stream().mapToInt(Repair::minutes).average().orElse(0);
boolean anyCargo = repairs.stream().anyMatch(r -> r.bike().startsWith("CARGO"));
int totalMinutes = repairs.stream().map(Repair::minutes).reduce(0, Integer::sum);
String bikes = repairs.stream().map(Repair::bike).distinct().collect(Collectors.joining(", "));
System.out.println("Parts used: " + allParts.size() + " " + allParts);
System.out.println("Kinds of part: " + kinds);
System.out.println("Longest repair: " + longest + " min, average: " + average + " min");
System.out.println("Any cargo bike? " + anyCargo + ", total: " + totalMinutes + " min");
System.out.println("Bikes repaired: " + bikes);
}
}Parts used: 7 [TUBE-700x25, PAD-ROAD, PAD-ROAD, CABLE-BRAKE, CHAIN-11, TUBE-700x25, BELL] Kinds of part: [BELL, CABLE-BRAKE, CHAIN-11, PAD-ROAD, TUBE-700x25] Longest repair: 60 min, average: 37.5 min Any cargo bike? true, total: 150 min Bikes repaired: CITY-2, CITY-4, CARGO-1
What this code does
flatMap joins the four lists of parts into one stream of seven codes, and distinct then sorted reduces them to the five kinds in alphabetical order. max and average on an IntStream return optional results because an empty stream has neither, so orElse supplies a default. reduce with Integer::sum gives the same 150 minutes that mapToInt(...).sum() would, and Collectors.joining previews next week's topic by building one string of bike names.
Streams or loops?
Streams are not always better than loops. They shine when the work is a chain of filtering, transforming and summarizing, and they let you name each step. A plain loop is clearer when the work needs early break with complicated conditions, changes several variables at once, or must throw checked exceptions, which lambdas cannot easily do. Ingrid's guidance for the shop's code was to prefer a stream when the pipeline fits on a few lines and reads like the question being asked, and a loop otherwise. parallelStream() exists too, but for the few thousand records a bike shop has it is slower, not faster, and it makes order and side effects harder to reason about; leave it until JAVA-240 has covered concurrency.
import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
int[] dailyRepairs = {6, 9, 4, 11, 7, 3, 8};
// Loop version
int busyLoop = 0;
for (int n : dailyRepairs) if (n >= 8) busyLoop++;
// Stream version
long busyStream = Arrays.stream(dailyRepairs).filter(n -> n >= 8).count();
// A range of numbers as a source
String days = IntStream.rangeClosed(1, 7)
.filter(d -> dailyRepairs[d - 1] >= 8)
.mapToObj(d -> "day " + d)
.collect(Collectors.joining(", "));
System.out.println("Busy days (loop): " + busyLoop);
System.out.println("Busy days (stream): " + busyStream);
System.out.println("Which: " + days);
System.out.println("Week total: " + IntStream.of(dailyRepairs).sum());
}
}Busy days (loop): 3 Busy days (stream): 3 Which: day 2, day 4, day 7 Week total: 48
What this code does
Both versions count the days with eight or more repairs and agree on three. IntStream.rangeClosed(1, 7) produces the day numbers, and mapToObj turns the chosen int values back into strings so they can be joined. For a job this small the loop and the stream are equally clear, which is the point: choose whichever reads more like the question.
By the end of the session Hamza had Odile's three questions as three short pipelines, and he had made the one mistake everyone makes once: storing a stream in a variable and using it twice. Next week's topic, collectors, answers the question he asked on the way out: how to count repairs of each kind in one pass.
Try it yourself
Shop time in September
Complete septemberHours with a stream pipeline: keep repairs whose month is 9, add up their minutes, and return the total in hours as a double (minutes divided by 60.0).
The program should print September: 3.0 hours.
import java.util.*;
public class Main {
record Repair(int ticket, int month, int minutes) { }
static double septemberHours(List<Repair> log) {
return 0; // replace with a stream pipeline
}
public static void main(String[] args) {
List<Repair> log = List.of(new Repair(501, 8, 75), new Repair(502, 9, 20), new Repair(503, 9, 45),
new Repair(504, 9, 15), new Repair(505, 9, 60), new Repair(506, 9, 40), new Repair(507, 10, 20));
System.out.println("September: " + septemberHours(log) + " hours");
}
}Try it yourself
The three longest repairs
Use one stream pipeline to print the ticket numbers of the three longest repairs, longest first, on one line separated by spaces.
Use sorted with a comparator on minutes reversed, then limit(3), then map to the ticket number. The program should print 505 501 503.
import java.util.*;
import java.util.stream.*;
public class Main {
record Repair(int ticket, int minutes) { }
public static void main(String[] args) {
List<Repair> log = List.of(new Repair(501, 75), new Repair(502, 20), new Repair(503, 45),
new Repair(504, 15), new Repair(505, 90), new Repair(506, 40));
String top = log.stream().map(r -> String.valueOf(r.ticket())).collect(Collectors.joining(" "));
System.out.println(top);
}
}Common mistakes
MistakeExpecting map or filter to run as soon as it is called.
InsteadRemember that intermediate operations are lazy; nothing runs until the terminal operation.
MistakeUsing a stream twice.
InsteadCreate a new stream from the source for each pipeline, or collect once into a list.
MistakeRemoving elements from the source list inside a pipeline.
InsteadNever modify the source; collect the elements you want into a new list.
MistakeDoing real work in peek or printing inside map.
InsteadKeep intermediate operations free of side effects and use peek only to debug.
MistakeReaching for parallelStream to make small jobs faster.
InsteadUse sequential streams for small data; parallel streams add cost and complexity.
Summary and key terms
- The Stream API describes work on a sequence of values as a pipeline: a source, zero or more intermediate operations and one terminal operation.
- Sources include collection.stream(), Stream.of, Arrays.stream and IntStream.range.
- Intermediate operations such as filter, map, mapToInt, flatMap, sorted, distinct and limit return new streams and are lazy, while terminal operations such as count, sum, toList, anyMatch, findFirst, reduce and collect produce the result.
- Elements flow through one at a time, so short-circuiting operations can stop early.
- A stream never modifies its source and can be used only once; a second terminal operation throws IllegalStateException.
- Primitive streams avoid boxing and offer sum, average and max.
- Prefer streams when the work is a readable chain of steps, and loops when it is not.
- Stream
- A one-time sequence of elements read from a source and processed by a pipeline of operations.
- Source
- Where a stream gets its elements, such as a list, an array or a range of numbers.
- Intermediate operation
- A lazy operation such as filter or map that returns a new stream.
- Terminal operation
- An operation such as count or toList that runs the pipeline and produces a result.
- Lazy evaluation
- Delaying work until a result is actually needed.
- Short-circuiting
- Stopping a pipeline early once the answer is known, as findFirst and anyMatch do.
- flatMap
- An operation that turns each element into a stream and joins the streams into one.
- IntStream
- A stream of primitive int values with methods such as sum and average.
- reduce
- A terminal operation that combines all elements into one value with an operation.
Practice problems
Work each problem on paper first, then reveal the answer to check.
Name the three parts of a stream pipeline.
Show answer
A source, intermediate operations and a terminal operation.
Why does building a pipeline with filter and map print nothing?
Show answer
Intermediate operations are lazy and run only when a terminal operation asks for results.
What happens if you call a terminal operation twice on one stream?
Show answer
The second call throws IllegalStateException.
Which operation turns a stream of bookings with part lists into one stream of parts?
Show answer
flatMap.
Why does mapToInt(...).max() return an optional value?
Show answer
An empty stream has no maximum.
Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.