Module 5: Java Streams & Lambdas (The Conveyor Belt)
📚 Module 5: Java Streams & Lambdas
Focus: Moving from “Loops” to “Conveyor Belts.”
Modern Java (Java 8+) introduced a way to process data using Functional Programming. This makes your code shorter, cleaner, and faster.
🏗️ Step 1: The Lambda (The “Mini-Job”)
A Lambda is just a tiny function without a name.
🧩 The Analogy: The Sticky Note
- Instead of hiring a full-time employee with a formal contract (a full class), you just write a tiny instruction on a Sticky Note and hand it to someone:
"Take this number and multiply it by 2."
In Java:
// Traditional
(int x) -> { return x * 2; }
// Modern (Short version)
x -> x * 2🏗️ Step 2: The Stream (The “Conveyor Belt”)
A Stream allows you to pass your data through a series of stations.
🧩 The Analogy: The Candy Factory
- Source: A bucket of raw candies (A List).
- Filter Station: “Only keep the red ones.”
- Map Station: “Wrap each candy in paper.”
- Terminal Station: “Put them all into a new box.”
In Java:
List<String> names = List.of("Alice", "Bob", "Charlie", "Dave");
List<String> result = names.stream()
.filter(name -> name.startsWith("C")) // Only keep Charlie
.map(name -> name.toUpperCase()) // Turn to CHARLIE
.toList(); // Finish the process🏗️ Step 3: Why use Streams?
- Readability: It reads like a sentence.
- No Loops: You don’t have to manage
for (int i=0; ...)counters. - Parallelism: You can change
.stream()to.parallelStream(), and Java will use all your CPU cores automatically!
🥅 Module 5 Review
- Lambda: A tiny, nameless function.
- Stream: A sequence of elements supporting functional operations.
- Filter: Removing items you don’t want.
- Map: Transforming items into something else.
- Collect/ToList: The final step that finishes the stream.