Skip to content

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

  1. Source: A bucket of raw candies (A List).
  2. Filter Station: “Only keep the red ones.”
  3. Map Station: “Wrap each candy in paper.”
  4. 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?

  1. Readability: It reads like a sentence.
  2. No Loops: You don’t have to manage for (int i=0; ...) counters.
  3. Parallelism: You can change .stream() to .parallelStream(), and Java will use all your CPU cores automatically!

🥅 Module 5 Review

  1. Lambda: A tiny, nameless function.
  2. Stream: A sequence of elements supporting functional operations.
  3. Filter: Removing items you don’t want.
  4. Map: Transforming items into something else.
  5. Collect/ToList: The final step that finishes the stream.