What is the Streams API?
Introduced in Java 8, the Streams API provides a functional way to process collections of objects. A Stream is not a data structure (it doesn't store data); instead, it conveys elements from a source (like a List or Set) through a pipeline of computational steps.
1. The Stream Pipeline
A stream pipeline consists of:
- Source: (e.g.,
list.stream()) - Intermediate Operations: Return a new stream (e.g.,
filter,map,sorted). These are lazy and don't execute until a terminal operation is called. - Terminal Operation: Produces a result or side-effect (e.g.,
collect,forEach,reduce,count).
java
2. Common Operations
Filter and Map
filter(Predicate): Keeps elements that match the condition.map(Function): Transforms each element into something else.
Reduce
Combines all elements into a single result (e.g., sum, concatenation).
java
FlatMap
Used when each element of a stream can produce multiple elements (e.g., a list of lists).
java
3. Parallel Streams
You can process data in parallel across multiple CPU cores by simply calling
.parallelStream() instead of .stream().CAUTION: Only use this for large datasets and stateless operations to avoid overhead and concurrency bugs.
4. Collectors
The
Collectors class provides many useful reduction operations:groupingBy: Group elements by a property (like SQLGROUP BY).joining: Concatenate strings.summarizingInt: Get min, max, average, and sum in one go.
java
Summary Checklist
- Streams are functional, not storage.
- Intermediate operations are lazy.
- Terminal operations trigger the execution.
- Use
mapfor transformations andfilterfor selection. - Use
flatMapfor nested structures. - Parallel streams can boost performance for heavy computations.