Streams API
A stream is a pipeline of operations over a sequence of values. You describe map, filter, and reduce steps. The source is traversed when a terminal operation runs.
Detailed Explanation
A loop says how to walk a collection. A stream says what to compute. list.stream().filter(User::active).map(User::name).toList() reads as "active users' names". The list is not copied into a new kind of collection. A stream is a view plus a plan. Until you call a terminal operation (toList, collect, forEach, reduce, count, findFirst), nothing walks the source.
Operations are intermediate or terminal. Intermediate ones (map, filter, flatMap, distinct, sorted, limit) return another stream and are lazy. Terminal ones consume the stream and produce a result or a side effect. A stream cannot be reused after a terminal operation. Create a new one from the source.
Stateless intermediate ops (map, filter) can run in parallel with parallel(). Stateful ones (sorted, distinct) need to see more of the data. Side effects inside map are a smell: they run lazily, they may run in another thread, and they may not run at all if a later findFirst short-circuits. Put side effects in forEach only when you accept that it is a loop in disguise.
Primitive streams (IntStream, LongStream, DoubleStream) avoid boxing. mapToInt is the bridge. Optional appears on findFirst, max, and reduce because the stream may be empty. collect(Collectors.toMap(...)) builds maps and needs a merge function when keys collide.
You reach for streams when the pipeline is a clear transformation and you do not need an index or a break with leftover state. You keep a loop when you are filling two structures, mutating as you go, or the body is a multi-step algorithm. Streams are not automatically faster. Parallel streams help CPU-heavy, stateless work on large data and hurt small lists and anything that touches a shared mutable structure.
The cost is allocation of pipeline objects and, for parallel, a fork-join pool that can starve other tasks if you block inside it. Debug by extracting named methods instead of nesting ten lambdas. Prefer toList() (unmodifiable, Java 16+) over collect(Collectors.toList()) when you do not need a mutable result.
Code Examples
import java.util.List;
public class ActiveNames {
record User(String name, boolean active) {}
public static void main(String[] args) {
List<User> users = List.of(
new User("Ana", true),
new User("Bo", false),
new User("Cy", true));
List<String> names = users.stream()
.filter(User::active)
.map(User::name)
.toList();
System.out.println(names); // prints: [Ana, Cy]
}
}import java.util.IntSummaryStatistics;
import java.util.stream.IntStream;
public class Stats {
public static void main(String[] args) {
IntSummaryStatistics s = IntStream.of(2, 4, 4, 8).summaryStatistics();
System.out.println(s.getSum()); // prints: 18
System.out.println(s.getCount()); // prints: 4
}
}Common Gotchas
A stream cannot be reused
a second terminal operation throws `IllegalStateException`. Call `stream()` again.
Side effects in `map` are lazy and may never run
do not put `list.add` inside `map`. Use `forEach` or, better, `collect`.
Parallel streams share the common ForkJoinPool
blocking I/O inside them stalls unrelated parallel work. Use a dedicated pool or stay sequential.
`toList()` is unmodifiable
`result.add(...)` throws. Use `collect(Collectors.toCollection(ArrayList::new))` when you must mutate.