Java Stream API
What a Stream Is
A stream (java.util.stream.Stream<T>) is a sequence of elements that you process with a chain of operations — filter these, transform those, sort, take the first three, add them up. Streams arrived in Java 8 together with lambdas, and they changed how most Java code that processes collections is written.
A stream is not a collection. It doesn't store elements; it describes a computation over elements that come from a source — a collection, an array, a file, a generator. The key properties:
| Property | Meaning |
|---|---|
| No storage | Elements flow through the pipeline from the source; the stream doesn't hold them |
| Doesn't modify the source | Filtering a stream of a list doesn't remove anything from the list |
| Lazy | Nothing happens until a terminal operation asks for a result |
| Single use | A stream can be traversed only once |
| Possibly infinite | A stream can produce elements without end, as long as something limits how many are used |
| Declarative | You describe what result you want; the library decides how to loop |
Loops versus Streams
Task: from a list of scores, take the three highest passing scores (50 or more) and label them.
import java.util.*;
public class First {
public static void main(String[] args) {
List<Integer> scores = List.of(91, 45, 78, 62, 39, 88, 70);
List<String> loop = new ArrayList<>();
List<Integer> sorted = new ArrayList<>(scores);
Collections.sort(sorted, Collections.reverseOrder());
for (int s : sorted) {
if (s >= 50) {
loop.add("PASS " + s);
if (loop.size() == 3) break;
}
}
System.out.println("loop: " + loop);
List<String> stream = scores.stream()
.filter(s -> s >= 50)
.sorted(Comparator.reverseOrder())
.limit(3)
.map(s -> "PASS " + s)
.toList();
System.out.println("stream: " + stream);
System.out.println("source unchanged: " + scores);
}
}
Output:
loop: [PASS 91, PASS 88, PASS 78]
stream: [PASS 91, PASS 88, PASS 78]
source unchanged: [91, 45, 78, 62, 39, 88, 70]
The loop mixes several concerns — copying the list (so the original isn't changed), sorting, filtering, counting and stopping — into one block of control flow, and the reader has to trace the variables to understand the goal.
The stream states each step in order: keep passing scores, sort highest first, take three, label them. Each step is one line, and the source list is untouched. This style is called internal iteration: the stream library runs the loop, and your code supplies only the behaviour for each step (as lambdas).
The Structure of a Pipeline
Every stream pipeline has three parts:
source → intermediate operations → terminal operation
scores.stream() .filter(...) .toList()
.sorted(...)
.limit(3)
.map(...)
| Part | What it is | Examples |
|---|---|---|
| Source | Where the elements come from | list.stream(), Arrays.stream(array), Stream.of(...), Files.lines(path), IntStream.range(0, 10) |
| Intermediate operations | Transform a stream into another stream; lazy, return a Stream | filter, map, flatMap, distinct, sorted, limit, skip, peek, takeWhile, dropWhile |
| Terminal operation | Produces a result or a side effect and ends the stream | toList, collect, forEach, count, sum, reduce, min, max, findFirst, anyMatch, allMatch, toArray |
A pipeline can have any number of intermediate operations, but exactly one terminal operation at the end. The next lessons cover each group: Stream Creation (sources), Stream Filter and Stream Map (the main intermediate operations), Stream Sort, and Stream Reduce, Stream Collect and Collectors Class (terminal operations).
Lazy Evaluation
Intermediate operations don't do any work when they're called; they only describe the pipeline. Work starts when a terminal operation requests results — and then only as much work as that result needs is done.
import java.util.*;
import java.util.stream.*;
public class Lazy {
public static void main(String[] args) {
Stream<String> pipeline = Stream.of("pen", "notebook", "ink", "backpack", "bag")
.filter(s -> { System.out.println(" filter " + s); return s.length() > 3; })
.map(s -> { System.out.println(" map " + s); return s.toUpperCase(); });
System.out.println("pipeline built, nothing has run yet");
Optional<String> first = pipeline.findFirst();
System.out.println("result: " + first.orElse("-"));
}
}
Output:
pipeline built, nothing has run yet
filter pen
filter notebook
map notebook
result: NOTEBOOK
Three things to notice:
- Nothing runs until
findFirst()is called — the first message appears before anyfilteroutput. - Elements flow through the pipeline one at a time, not stage by stage.
penis filtered (and rejected);notebookis filtered and then immediately mapped. The stream doesn't first filter all five elements and then map the survivors. - Short-circuiting: once
findFirsthas a result, processing stops.ink,backpackandbagare never examined.
That's why streams can be efficient even with long pipelines: the work is fused into a single pass, and short-circuiting operations (findFirst, findAny, anyMatch, allMatch, noneMatch, limit) avoid unnecessary work.
Laziness makes infinite streams possible
import java.util.stream.*;
public class Infinite {
public static void main(String[] args) {
System.out.println(Stream.iterate(1, n -> n * 2).limit(10).toList());
System.out.println(IntStream.iterate(1, n -> n + 1)
.filter(n -> n % 7 == 0 && n % 5 == 0)
.findFirst().getAsInt());
}
}
Output:
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
35
Stream.iterate(1, n -> n * 2) describes the endless sequence 1, 2, 4, 8, ... — it's safe because limit(10) stops it. The second pipeline searches the infinite sequence of positive integers for the first number divisible by both 7 and 5, and stops as soon as it finds 35. Without a limiting or short-circuiting operation, an infinite stream would run forever.
Stateful operations change the flow
Most intermediate operations are stateless: each element is handled independently (filter, map). A few are stateful: they need to see other elements first (sorted, distinct). Sorting can't produce its first element until it has seen all of them:
import java.util.stream.*;
public class Order {
public static void main(String[] args) {
Stream.of("c", "a", "b")
.peek(s -> System.out.println(" before sorted: " + s))
.sorted()
.peek(s -> System.out.println(" after sorted: " + s))
.forEach(s -> System.out.println(" forEach: " + s));
}
}
Output:
before sorted: c
before sorted: a
before sorted: b
after sorted: a
forEach: a
after sorted: b
forEach: b
after sorted: c
forEach: c
All elements pass through the first stage and are buffered by sorted; then they continue one by one. peek (which runs an action on each element as it passes) is useful exactly for this kind of debugging. Stateful operations need memory proportional to the stream size and can't be used on infinite streams.
A Stream Can Be Used Only Once
import java.util.stream.*;
public class Once {
public static void main(String[] args) {
Stream<String> names = Stream.of("Asha", "Ravi");
System.out.println(names.count());
try {
names.count();
} catch (IllegalStateException e) {
System.out.println("IllegalStateException: " + e.getMessage());
}
}
}
Output:
2
IllegalStateException: stream has already been operated upon or closed
After a terminal operation, the stream is consumed. A stream is like an iterator, not a collection: to process the data again, create a new stream from the source (list.stream() again). This is also why storing a Stream in a field or variable for later reuse is usually a mistake — store the collection, or a Supplier<Stream<T>>, instead.
Avoid Side Effects in Stream Operations
Lambdas passed to stream operations should compute results from their inputs, not modify outside state. Code that adds to an external list from forEach or map works in simple sequential cases, but it's fragile, and it breaks completely when the stream is made parallel:
import java.util.*;
import java.util.stream.*;
public class Side {
public static void main(String[] args) {
List<Integer> numbers = IntStream.rangeClosed(1, 10_000).boxed().toList();
List<Integer> unsafe = new ArrayList<>();
numbers.parallelStream().filter(n -> n % 2 == 0).forEach(unsafe::add);
List<Integer> safe = numbers.parallelStream().filter(n -> n % 2 == 0).toList();
System.out.println("collected with toList: " + safe.size() + " (expected 5000)");
System.out.println("added from forEach is unreliable; size this run: " + unsafe.size());
}
}
Output from one run (the second number varies from run to run, and the forEach version can even throw an exception):
collected with toList: 5000 (expected 5000)
added from forEach is unreliable; size this run: 4987
ArrayList isn't thread-safe, so concurrent add calls from the parallel stream lose elements. Letting the stream build the result with a terminal operation — toList(), collect(...), sum() — is correct in both sequential and parallel streams. The rule: use the result of the terminal operation; don't mutate external state from inside the pipeline. forEach is meant for the final action on each element (printing, sending), not for building collections.
Primitive Streams
Besides Stream<T> there are three specialised streams for primitive values: IntStream, LongStream and DoubleStream. They avoid boxing every number into an object and provide numeric operations that Stream<T> doesn't have:
int total = IntStream.rangeClosed(1, 100).sum(); // 5050
double avg = sales.stream().mapToDouble(Sale::amount).average() // OptionalDouble
.orElse(0);
IntSummaryStatistics stats = IntStream.of(91, 45, 78).summaryStatistics(); // min, max, average, sum, count
mapToInt, mapToLong and mapToDouble convert a Stream<T> into a primitive stream; boxed() converts back. The Stream Map lesson covers these conversions.
When Streams Fit — and When They Don't
Streams are a good fit for:
- transforming, filtering, grouping and aggregating collections — the bulk of business data processing;
- pipelines over files (
Files.lines) and other large or generated sources; - code that reads as a sequence of steps.
A plain loop is often better when:
- the logic needs to break out early in complex ways, or modify local variables as it goes;
- you need checked exceptions from the loop body (lambdas can't throw them easily — see the Functional Interfaces lesson);
- the operation is a simple
forover indices, or performance-critical code where a loop is measurably faster; - the stream version would need long, nested lambdas — readability is the main benefit of streams, so a stream that's harder to read than the loop is the wrong choice.
Practical Example: Sales Analytics
Business reporting — totals, averages, groupings, top performers — is where streams are used most. This example answers several questions about a month of course sales, each with a short pipeline.
import java.time.*;
import java.util.*;
import java.util.stream.*;
public class Sales {
record Sale(String course, String city, double amount, LocalDate date, boolean refunded) { }
public static void main(String[] args) {
List<Sale> sales = List.of(
new Sale("Java", "Chennai", 4999, LocalDate.of(2026, 11, 2), false),
new Sale("Django", "Madurai", 5999, LocalDate.of(2026, 11, 3), false),
new Sale("Java", "Coimbatore", 4999, LocalDate.of(2026, 11, 5), true),
new Sale("Docker", "Chennai", 3999, LocalDate.of(2026, 11, 8), false),
new Sale("Java", "Chennai", 4499, LocalDate.of(2026, 11, 9), false),
new Sale("Django", "Chennai", 5999, LocalDate.of(2026, 10, 30), false),
new Sale("Python", "Salem", 2999, LocalDate.of(2026, 11, 12), false));
LocalDate from = LocalDate.of(2026, 11, 1);
List<Sale> november = sales.stream()
.filter(s -> !s.refunded())
.filter(s -> !s.date().isBefore(from))
.toList();
double revenue = november.stream().mapToDouble(Sale::amount).sum();
long count = november.stream().count();
OptionalDouble average = november.stream().mapToDouble(Sale::amount).average();
Map<String, Double> byCourse = november.stream()
.collect(Collectors.groupingBy(Sale::course, TreeMap::new, Collectors.summingDouble(Sale::amount)));
String topCity = november.stream()
.collect(Collectors.groupingBy(Sale::city, Collectors.counting()))
.entrySet().stream()
.max(Map.Entry.comparingByValue())
.map(Map.Entry::getKey).orElse("-");
List<String> bigTickets = november.stream()
.filter(s -> s.amount() >= 5000)
.map(s -> s.course() + "@" + s.city())
.distinct()
.toList();
System.out.printf("November: %d sales, revenue %.2f, average %.2f%n", count, revenue, average.orElse(0));
System.out.println("by course: " + byCourse);
System.out.println("top city: " + topCity);
System.out.println("big tickets: " + bigTickets);
}
}
Output:
November: 5 sales, revenue 22495.00, average 4499.00
by course: {Django=5999.0, Docker=3999.0, Java=9498.0, Python=2999.0}
top city: Chennai
big tickets: [Django@Madurai]
How each question is answered:
- Selecting the data: two
filtersteps remove refunded sales and sales before November. The result is collected once withtoList()and reused, because each stream can only be used once — every later question starts a new stream from this list. - Totals and averages:
mapToDouble(Sale::amount)switches to aDoubleStream, which hassum()andaverage().average()returns anOptionalDouble, because an empty stream has no average (Optional Class lesson). - Revenue per course:
Collectors.groupingBywith a downstreamsummingDoublecollector groups and totals in one step;TreeMap::newsorts the courses (Collectors Class lesson). - Top city: count sales per city, then stream the map's entries and pick the entry with the highest value. Chennai has 2 November sales.
- Big tickets: filter, transform into labels, and remove duplicates with
distinct. The October Django sale was already excluded.
Each pipeline is a few lines, the source list is never modified, and the steps read in the same order as the question they answer.