8.4 Stream API
← Back to Chapter 8: Java 8 Features
The Stream API (java.util.stream) represents a powerful, declarative mechanism for processing sequences of elements. Instead of writing explicit loops with conditional logic, you define high-level transformation pipelines.
STREAM API
|
┌── ─────┴───────┐
↓ ↓
SOURCE PIPELINE
|
┌──────┴──────┐
↓ ↓
INTERMEDIATE TERMINAL
| |
filter/map/... collect/toList
|
LAZY
What is Streams?
Stream API is a way to process data from a collection in a clean, readable and functional style.
Suppose you have:
List<Integer> numbers = [10, 15, 20, 25, 30]
You want:
Find all numbers greater than 20 and convert them into their squares.
Without Stream:
for each number
if number > 20
calculate square
add to another list
With Stream:
numbers.stream()
.filter(n -> n > 20)
.map(n -> n * n)
.toList();
Result:
[625, 900]
A Stream itself does not store data. It takes data from a source such as a collection, array, generator, etc., and passes it through operations.