Nearby lessons
94 of 125Java - Stream API
📌 What You Will Learn
- Lambda expressions — the big change
- Functional interfaces
- Default and static methods in interfaces
- The four workhorses: Predicate, Function, Consumer, Supplier
- Method references (::)
- The Stream API for processing collections
- Optional — safe null handling
- The new Date and Time API
Stream API is a core concept of the Java language. This lesson explains The Stream API — Processing Collections with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.
The Stream API — Processing Collections
A Stream is a flow of elements we can process with chain-like steps: filter → sort → map → collect. The data source stays unchanged; the stream works on a copy-like flow.
In simple words: A stream pipeline never changes the original collection. filter, map and sorted work on a flow of elements, and only collect(...) builds a new result list at the end.
The pipeline is easy to read like English: take the numbers, keep only those above 10, double each, sort them, and collect.
Important Stream Operations
| Operation | What it does |
|---|---|
| filter(predicate) | Keep only matching elements |
| map(function) | Convert every element |
| sorted() | Sort the stream |
| distinct() | Remove duplicates |
| limit(n) | Take only the first n elements |
| count() | How many elements are there |
| forEach(consumer) | Do something with each element |
| collect(...) | Turn the stream back into a list/set/map |
| reduce(...) | Combine all elements into one (like sum) |
Example01
The Stream API — Processing Collections
Example02
📝 Key Takeaways
- Lambda = a function without a name; (params) -> logic.
- Functional interface = one abstract method, so a lambda can implement it.
- Interfaces now have default and static methods with bodies.
- Predicate (test), Function (apply), Consumer (accept), Supplier (get) are the four core functional interfaces.
- Method references (::) are shorthand for lambdas.
- Streams process collections with filter/map/sorted/collect pipelines.
- Optional prevents NullPointerException with orElse/isPresent.
- java.time (LocalDate, LocalDateTime) replaces the old Date/Calendar cleanly.
🧠 Test Your Knowledge
1 QuestionsProgress: 0 / 1