Java Streams (introduced in Java 8) provide a functional, declarative way to process collections. They allow writing cleaner and more readable code using pipelines like:
source → intermediate operations → terminal operation
Streams do not modify original data — they create a new result.
Key Features of Streams
- Supports functional programming style
- Works with Collections, Arrays, I/O data
- Lazy evaluation (executed only when needed)
- Supports parallel processing
- No modification of original data
- Readable pipelines for data processing
Stream Pipeline
collection.stream()
.filter(...)
.map(...)
.sorted(...)
.collect(...);
Source → stream()
Intermediate Ops → filter(), map(), sorted()
Terminal Ops → collect(), forEach(), reduce()
Common Intermediate Operations
| Method | Purpose |
|---|---|
filter() |
Keep only matching elements |
map() |
Transform elements |
sorted() |
Sort elements |
distinct() |
Remove duplicates |
limit() / skip()
|
Pagination-like usage |
peek() |
Debug/log values |
Common Terminal Operations
| Method | Purpose |
|---|---|
collect() |
Convert to List/Set/Map |
forEach() |
Loop through items |
count() |
Count elements |
min() / max()
|
Find smallest/largest |
reduce() |
Aggregate into a single result |
toArray() |
Convert to array |
Examples
Filter & Collect
List<Integer> evens = nums.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
Map (Transform)
List<Integer> doubled = nums.stream()
.map(n -> n * 2)
.collect(Collectors.toList());
Reduce (Sum)
int sum = nums.stream()
.reduce(0, Integer::sum);
Sorting
List<String> sorted = names.stream()
.sorted()
.collect(Collectors.toList());
Parallel Streams
list.parallelStream()
.forEach(System.out::println);
👉 Used for large data processing
⚠️ Avoid for small collections (thread overhead)
⚠️ Be careful with shared mutable data
When to Use Java Streams?
✔ Cleaner & readable code
✔ Complex data transformation
✔ Large dataset processing
✔ Aggregations and filtering
✔ Multi-core parallel processing (parallelStream)
❌ Avoid when:
- Debugging is complex
- Performance is critical with small data
- Code readability becomes worse
Summary Table
| Concept | Key Idea |
|---|---|
| Stream | Flow of data without storage |
| Intermediate Op | Returns another Stream |
| Terminal Op | Produces final result |
| Immutable | Original data not changed |
| Lazy Eval | Runs only when needed |
| Functional | Uses lambda expressions |
Top comments (0)