Lesson 49: Deep Dive into the Java Streams API
The Streams API (Java 8+) is one of the most powerful features for processing sequences of data (collections or arrays) in a functional and declarative style.
1. What is a Stream?
A stream is a sequence of elements that supports sequential and parallel aggregate operations. Crucially, a stream:
- Is not a data structure: It doesn't store data; it pipelines data from a source (like a List).
- Is functional: Operations don't modify the source data.
- Is lazy: Operations are only executed when a terminal operation is called.
2. Stream Pipeline Structure
A stream pipeline consists of three parts:
- Source: A collection, array, or I/O resource (
list.stream()). - Intermediate Operations: Transform the stream and return a new stream (e.g.,
filter,map,sorted). These are lazy. - Terminal Operation: Produces a result or side effect (e.g.,
forEach,collect,reduce,count). This triggers the execution.
3. Core Intermediate Operations
filter(): Selects elements matching a given condition (Predicate).map(): Transforms each element into a new value (Function).sorted(): Sorts the elements.
java
List
List
System.out.println(result); // Output: [APPLE, BANANA]
4. The reduce() Operation
reduce() combines all elements in the stream to produce a single result (e.g., sum, product, concatenation).
java
List