Java Stream API Features with Examples
The Java Stream API is a set of types in the java.util.stream package, introduced in Java 8, for processing sequences of elements with chained operations such as filter(), map() and collect(). Its central type is the Stream<T> interface, supported by IntStream, LongStream, DoubleStream and the Collectors utility class.
This tutorial explains the features that make streams different from loops and collections: no storage, a source that stays unchanged, lazy and short-circuiting execution, possibly infinite sources, single use, internal iteration and built-in parallelism. Each feature is shown with a short program that was compiled and run on Java 25.
1. Key Features of the Stream API
| Feature | What it means in practice | Since |
|---|---|---|
| Declarative pipelines | You describe what result you want with named steps instead of writing loop mechanics. | Java 8 |
| No storage | A stream holds no elements; it pulls them from a source such as a collection, array, generator or file. | Java 8 |
| Non-interference | Operations produce new values; the source collection is not modified. | Java 8 |
| Lazy evaluation | Intermediate operations run only when a terminal operation asks for a result. | Java 8 |
| Short-circuiting | Operations such as limit(), findFirst() and anyMatch() can stop early. | Java 8 |
| Possibly unbounded | Stream.iterate() and Stream.generate() can describe endless sequences. | Java 8 |
| Single use | A stream can be consumed by only one terminal operation. | Java 8 |
| Internal iteration | The library controls the loop, which lets it optimise and parallelise the work. | Java 8 |
| Parallel execution | parallel() or parallelStream() splits work across the common ForkJoinPool. | Java 8 |
| Primitive streams | IntStream, LongStream and DoubleStream avoid boxing and add sum(), average() and statistics. | Java 8 |
| Rich collectors | Collectors groups, partitions, joins and summarises results. | Java 8 |
| Conditional slicing | takeWhile(), dropWhile(), ofNullable() and a bounded iterate(). | Java 9 |
| Shortcuts | teeing() (Java 12), toList() and mapMulti() (Java 16). | Java 12, 16 |
| Custom intermediate operations | Stream.gather() with Gatherer lets you write your own intermediate steps. | Java 24 |
2. How These Features Work Together
Most of these features come from one design decision: a stream is a description of a computation, not a container. When you call filter() or map(), Java records a new stage and returns a new Stream object. Nothing is read from the source yet. The terminal operation, such as collect() or count(), then pulls elements through the stages one at a time.
Because the library owns the loop, it can stop as soon as the answer is known, skip work it does not need, and split the source into parts for parallel processing. The cost of this design is that a stream can be traversed only once: after the terminal operation, the description is used up.
3. Java Examples
Example 1: The source stays unchanged (Java 9+)
A weather service keeps a list of temperature readings and needs only the hot ones, without changing the original data.
import java.util.List;
import java.util.stream.Collectors;
public class SourceUnchangedDemo {
public static void main(String[] args) {
List<Integer> readings = List.of(18, 25, 31, 22, 35, 27);
List<Integer> hotReadings = readings.stream()
.filter(temperature -> temperature > 26)
.collect(Collectors.toList());
System.out.println("Hot readings: " + hotReadings);
System.out.println("Original list: " + readings);
}
}
Hot readings: [31, 35, 27] Original list: [18, 25, 31, 22, 35, 27]
How it works: filter() builds a new stream and collect() builds a new list. The readings list is only read, so it prints exactly as it was created. List.of() needs Java 9; the stream calls themselves work on Java 8.
Example 2: Laziness and short-circuiting on an endless source
Find the first four multiples of 7 whose last digit is 1, starting from an endless sequence of positive numbers.
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class LazyEndlessDemo {
public static void main(String[] args) {
AtomicInteger generated = new AtomicInteger();
List<Integer> result = Stream.iterate(1, n -> n + 1) // 1, 2, 3, ... forever
.map(n -> {
generated.incrementAndGet();
return n * 7;
})
.filter(multiple -> multiple % 10 == 1)
.limit(4)
.collect(Collectors.toList());
System.out.println("First four: " + result);
System.out.println("Numbers generated: " + generated.get());
}
}
First four: [21, 91, 161, 231] Numbers generated: 33
How it works: The source is infinite, yet the program ends. limit(4) is short-circuiting: once four matches have passed it, the pipeline stops asking iterate() for more numbers. Only 33 numbers were generated, because 7 × 33 = 231 is the fourth match. The counter is used only to make the laziness visible.
Example 3: Getting a fresh stream every time with a Supplier
A dashboard needs both the number of active users and their names. A stream can be used once, so the pipeline is wrapped in a Supplier.
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class StreamSupplierDemo {
public static void main(String[] args) {
Supplier<Stream<String>> activeUsers = () -> Stream.of("asha", "ravi", "meera", "john", "kiran")
.filter(user -> !user.equals("john"));
long count = activeUsers.get().count();
String names = activeUsers.get()
.map(String::toUpperCase)
.collect(Collectors.joining(", "));
System.out.println("Active users: " + count);
System.out.println("Names: " + names);
}
}
Active users: 4 Names: ASHA, RAVI, MEERA, KIRAN
How it works: Each call to activeUsers.get() builds a brand-new pipeline, so the two terminal operations never touch the same stream object. This keeps the single-use rule without repeating the filtering code.
Example 4: Built-in aggregation with Collectors (Java 16+)
A bookstore wants the average price of its books per genre, sorted by genre name.
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class GenreAveragePrice {
record Book(String title, String genre, double price) { }
public static void main(String[] args) {
List<Book> books = List.of(
new Book("Stream Recipes", "Tech", 650.0),
new Book("Monsoon Letters", "Fiction", 320.0),
new Book("Cloud Patterns", "Tech", 780.0),
new Book("The Quiet Harbour", "Fiction", 410.0),
new Book("Data Craft", "Tech", 540.0));
Map<String, Double> averageByGenre = books.stream()
.collect(Collectors.groupingBy(Book::genre, TreeMap::new,
Collectors.averagingDouble(Book::price)));
averageByGenre.forEach((genre, average) ->
System.out.printf("%-8s %.2f%n", genre, average));
}
}
Fiction 365.00 Tech 656.67
How it works: groupingBy() splits the books into one group per genre, TreeMap::new keeps the genres sorted, and averagingDouble() reduces each group to a single number. The record needs Java 16.
Example 5: Parallel execution with one method call
Compute the sum of the squares of the numbers from 1 to 1,000,000 sequentially and in parallel, and confirm the results match.
import java.util.stream.LongStream;
public class ParallelSumDemo {
public static void main(String[] args) {
long sequential = LongStream.rangeClosed(1, 1_000_000)
.map(n -> n * n)
.sum();
long parallel = LongStream.rangeClosed(1, 1_000_000)
.parallel()
.map(n -> n * n)
.sum();
System.out.println("Sequential: " + sequential);
System.out.println("Parallel: " + parallel);
System.out.println("Same result: " + (sequential == parallel));
}
}
Sequential: 333333833333500000 Parallel: 333333833333500000 Same result: true
How it works: Adding parallel() is the only change. Addition is associative and each square is independent, so the parallel version splits the range, sums each part on a different thread and combines the partial sums into the same answer. LongStream avoids boxing every number.
4. Real-World Use Cases
- Product catalogues: filter products by category, price range and stock, and return a sorted page of results without copying the catalogue.
- Banking reports: group transactions by account and type, then sum or average the amounts with collectors.
- Log analysis: read a large log file lazily with
Files.lines()and stop as soon as the first error after a timestamp is found. - Batch calculations: run CPU-heavy, independent calculations, such as risk scores for many portfolios, on a parallel stream after measuring the gain.
5. Important Points
- Empty sources are fine. A pipeline on an empty list simply returns an empty list, a count of 0 or an empty
Optional. - Nulls are not filtered for you. A
nullelement reaches every lambda; calling a method on it throwsNullPointerException. - Order depends on the source. A
Listhas an encounter order; aHashSetdoes not, so its stream order is unspecified. - Do not modify the source during the pipeline. Changing a list while streaming it can throw
ConcurrentModificationException. - Lambdas should be stateless. Results must not depend on variables that change while the stream runs, especially in parallel.
- Performance: for tiny, simple loops a stream adds a small overhead; its value is clarity, not raw speed.
6. Stream Features Compared with Loops
| Need | Plain loop | Stream |
|---|---|---|
| Transform and filter a list | Manual result list | filter().map().toList() |
| Stop at the first match | break | findFirst(), anyMatch() |
| Group and summarise | Maps and counters by hand | Collectors.groupingBy() |
| Endless sequences | while (true) with a counter | iterate() plus limit() |
| Run in parallel | Threads or executors | parallel() |
| Checked exceptions, indexes | Natural | Awkward |
Choose a stream when the task is a transformation or a summary of data; choose a loop when you need indexes, checked exceptions or complex early exits. See Stream vs For Loop for a deeper comparison.
7. Common Mistakes and Best Practices
Modifying the source inside the pipeline
Adding to or removing from the list that feeds the stream breaks non-interference:
List<String> tasks = new ArrayList<>(List.of("build", "test", "deploy"));
tasks.stream().forEach(task -> tasks.add(task + "-retry")); // ConcurrentModificationException
Build the extra elements into a new list instead:
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class NoInterferenceFix {
public static void main(String[] args) {
List<String> tasks = new ArrayList<>(List.of("build", "test", "deploy"));
List<String> withRetries = tasks.stream()
.flatMap(task -> Stream.of(task, task + "-retry"))
.collect(Collectors.toList());
System.out.println(withRetries);
}
}
[build, build-retry, test, test-retry, deploy, deploy-retry]
Other mistakes to avoid
- Expecting work without a terminal operation.
orders.stream().map(this::send)sends nothing until a terminal operation runs. - Forgetting
limit()on an endless source.Stream.generate(...).toList()never finishes and eventually runs out of memory. - Using
parallel()by habit. For small lists or I/O-bound work, the thread coordination costs more than it saves. - Holding on to a stream. Store a collection or a
Supplier<Stream>, never a stream object in a field.
8. Summary
- A stream is a lazy description of a computation over a source; it stores nothing and does not change the source.
- Short-circuiting operations let streams stop early and even work with infinite sources.
- A stream can be consumed once; wrap the pipeline in a
Supplierwhen you need it again. - Collectors and primitive streams cover grouping, averaging and statistics without hand-written maps and counters.
- Parallel execution is one call away, but it pays off only for large, independent, CPU-heavy work.
9. References
Frequently Asked Questions (FAQ)
Q1. What are the main features of the Java Stream API?
Streams store no data, leave their source unchanged, evaluate intermediate operations lazily, can short-circuit, can represent infinite sequences, can be consumed only once, use internal iteration and can run in parallel with a single method call.
Q2. Why are Java streams called lazy?
Intermediate operations such as filter() and map() only add a stage to the pipeline. No element is read until a terminal operation such as collect() or count() runs, and then only as many elements as the result needs are processed.
Q3. Does a stream modify the original collection?
No. Stream operations read the source and produce new values or new collections. The source stays unchanged, and it must not be modified while the stream is running, because that can throw ConcurrentModificationException.
Q4. What is internal iteration in streams?
With a loop your code asks for each element and decides what to do; that is external iteration. With a stream you pass the rules as lambdas and the library runs the loop itself, which allows lazy evaluation, short-circuiting and parallel execution.
Q5. Which Stream API features were added after Java 8?
Java 9 added takeWhile(), dropWhile(), ofNullable() and a three-argument iterate(). Java 12 added Collectors.teeing(), Java 16 added toList() and mapMulti(), and Java 24 finalised Stream.gather() for custom intermediate operations.