Stream API in Java 8
The Stream API, added in Java 8 (JEP 107), lets you process collections declaratively: you describe what to do with the data, such as filter, transform and summarise, and the library handles the looping.
This tutorial covers the structure of a stream pipeline, the difference between intermediate and terminal operations, lazy evaluation and primitive streams. For every individual operation, see the dedicated Stream API tutorials on this site.
1. Why Was the Stream API Added?
Processing collections with loops mixes the business rule with bookkeeping: index variables, temporary lists and accumulators. Streams express the same rule as a chain of steps, which is shorter, easier to read and can run in parallel with one method call.
2. Structure of a Stream Pipeline
result = source.stream() // 1. source
.filter(predicate) // 2. intermediate operations (lazy)
.map(function)
.collect(Collectors.toList()); // 3. terminal operation (runs the pipeline)
| Part | Examples | Returns |
|---|---|---|
| Source | list.stream(), Arrays.stream(arr), Stream.of(...) | a Stream |
| Intermediate | filter, map, sorted, distinct, limit | a new Stream (lazy) |
| Terminal | collect, forEach, count, reduce, findFirst | a result or side effect |
3. Practical Examples
Example 1: A complete pipeline
The program finds customers from Pune with orders above 1000, and also computes totals with a primitive DoubleStream.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class StreamPipeline {
static class Order {
final String customer;
final String city;
final double amount;
Order(String customer, String city, double amount) {
this.customer = customer;
this.city = city;
this.amount = amount;
}
}
public static void main(String[] args) {
List<Order> orders = Arrays.asList(
new Order("Asha", "Pune", 1200),
new Order("Ravi", "Delhi", 450),
new Order("Meera", "Pune", 3000),
new Order("John", "Kochi", 800),
new Order("Asha", "Pune", 650));
// source -> intermediate operations -> terminal operation
List<String> bigPuneCustomers = orders.stream()
.filter(o -> o.city.equals("Pune")) // keep Pune orders
.filter(o -> o.amount > 1000) // keep large ones
.map(o -> o.customer) // Order -> String
.distinct()
.sorted()
.collect(Collectors.toList());
System.out.println("Big Pune customers: " + bigPuneCustomers);
double total = orders.stream().mapToDouble(o -> o.amount).sum();
long smallOrders = orders.stream().filter(o -> o.amount < 1000).count();
System.out.println("Total revenue : " + total);
System.out.println("Orders under 1000 : " + smallOrders);
}
}
Big Pune customers: [Asha, Meera] Total revenue : 6100.0 Orders under 1000 : 3
Example 2: Lazy evaluation and short-circuiting
peek shows when each element is actually processed. Building the pipeline does nothing; findFirst pulls elements one by one and stops at the first PDF.
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class LazyEvaluation {
public static void main(String[] args) {
List<String> files = Arrays.asList("a.txt", "b.pdf", "c.pdf", "d.doc");
// Nothing runs until a terminal operation is called
Stream<String> pipeline = files.stream()
.peek(f -> System.out.println(" checking " + f))
.filter(f -> f.endsWith(".pdf"));
System.out.println("Pipeline built, no element processed yet");
// findFirst() stops as soon as one match is found (short-circuit)
Optional<String> firstPdf = pipeline.findFirst();
System.out.println("First PDF: " + firstPdf.get());
// Primitive streams avoid boxing; IntStream.rangeClosed builds numbers
int sumOfSquares = IntStream.rangeClosed(1, 5).map(n -> n * n).sum();
System.out.println("Sum of squares 1..5 = " + sumOfSquares);
}
}
Pipeline built, no element processed yet checking a.txt checking b.pdf First PDF: b.pdf Sum of squares 1..5 = 55
Only a.txt and b.pdf are checked. The remaining files are never touched, which is why stream pipelines can be efficient even on large sources.
4. How a Stream Processes Elements
5. Important Points and Best Practices
- A stream can be consumed only once; reusing it throws
IllegalStateException. - Streams do not modify their source; they produce new results.
- Avoid side effects inside
maporfilter; use collectors to build results. - Use
IntStream,LongStreamandDoubleStreamfor numbers to avoid boxing. parallelStream()helps only for large, CPU-heavy, independent work; measure before using it.
6. Summary
- Streams process data declaratively and were added in Java 8 (JEP 107).
- A pipeline has a source, zero or more lazy intermediate operations and one terminal operation.
- Nothing runs until the terminal operation; short-circuit operations stop early.
- Streams are single-use and do not change their source.
Related Tutorials
7. References
Frequently Asked Questions (FAQ)
Q1. What is the difference between a collection and a stream?
A collection stores data in memory. A stream does not store data; it describes a computation over a source and produces a result when a terminal operation runs.
Q2. What are intermediate and terminal operations?
Intermediate operations such as filter and map return a new stream and are lazy. Terminal operations such as collect and count trigger processing and produce a result.
Q3. Can a stream be reused?
No. After a terminal operation the stream is consumed, and calling another operation throws IllegalStateException. Create a new stream from the source instead.
Q4. What does lazy evaluation mean in streams?
Intermediate operations do not run when they are declared. Elements are processed only when a terminal operation requests them, which allows short-circuiting and avoids unnecessary work.