Introduction
The Stream API, introduced in Java 8 through java.util.stream, changed how we process collections. Instead of imperative loops, streams provide a declarative pipeline that is concise and expressive.
What Is a Stream?
A stream is a sequence of elements processed through chained operations. Unlike collections, streams do not store data. They define how data flows from one operation to another.
Core Stream Phases
- Source: where data comes from (
List,Set, arrays, etc.). - Intermediate Operations: lazy transformations such as
filter,map,sorted. - Terminal Operations: produce a result, such as
collect,forEach, orreduce.
Example
List<String> names = Arrays.asList("Anna", "Bob", "Charlie", "David");
List<String> filteredNames = names.stream()
.filter(name -> name.startsWith("A"))
.sorted()
.collect(Collectors.toList());
System.out.println(filteredNames); // [Anna]
Benefits of Streams
- Concise code: Less boilerplate than manual iteration.
- Parallel processing:
parallelStream()can improve performance for large workloads. - Immutability-friendly: Operations usually avoid mutating source data.
- Composability: Pipelines are easier to understand and extend.
Conclusion
Streams provide a powerful and modern approach to Java data processing. By combining declarative pipelines with built-in functional operators, they help you write code that is easier to read, maintain, and optimize.