Skip to content

Lambda Expressions πŸš€

Mentor's Note: Lambda expressions (introduced in Java 8) are the biggest change in Java's history. They allow you to write 10 lines of code in just 1 line. It's like switching from a typewriter to a modern laptop! πŸ’‘


🌟 The Scenario: The Delivery Order πŸ“

Imagine you are ordering food.

  • The Old Way (Anonymous Class): You have to sign a long paper contract, write your full name, address, and date, just to say "I want Pizza." πŸ“¦
  • The New Way (Lambda): You just send a text: Me -> Pizza. πŸ“¦
  • The Result: You get your food faster with less effort. The -> (Arrow) is your message from you to the action. βœ…

πŸ“– Concept Explanation

1. What is a Lambda?

A lambda expression is a short block of code which takes in parameters and returns a value. It is essentially an Anonymous Method (a method without a name).

2. Syntax

(parameter1, parameter2) -> { code block }

  • Parameters: The input. πŸ“₯
  • Arrow ->: Connects input to the logic.
  • Body: What to do with the input. βš™οΈ

🎨 Visual Logic: The Shrink Ray ⚑

graph LR
    A["Before: <br/>public void run() { <br/> System.out.println('Hi'); <br/>}"] -- Shrink Ray! --> B["After: <br/>() -> System.out.println('Hi')"]
    style B fill:#dfd,stroke:#333

πŸ’» Implementation: The Lambda Lab

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(5);
        numbers.add(9);
        numbers.add(8);

        // πŸ›’ Scenario: Print each item
        // πŸš€ Action: Using a Lambda inside forEach
        numbers.forEach( (n) -> { System.out.println("Processing: " + n); } );

        // πŸ›οΈ Outcome: Clean, readable code without manual loops.
    }
}
// πŸš€ Action: Find items matching a condition
numbers.removeIf(n -> n % 2 == 0); // Remove all even numbers! βœ‚οΈ

πŸ“Š Sample Dry Run

List Lambda Logic Result
[5, 10, 15] n -> n > 8 [10, 15]
["Hi", "Bye"] s -> s.length() [2, 3]

πŸ“ˆ Technical Analysis

  • Functional Interfaces: Lambdas only work with interfaces that have Exactly One abstract method (e.g., Runnable, Comparator).
  • Target Type: Java automatically guesses the data type of the lambda based on the context! 🧠

🎯 Practice Lab πŸ§ͺ

Task: The Custom Greeter

Task: Given a list of names, use forEach and a Lambda to print "Hello, [Name]!" for every person in the list. Hint: names.forEach(name -> ...);. πŸ’‘


πŸ’‘ Interview Tip πŸ‘”

"Interviewers love asking: 'Why use Lambdas?' Answer: They enable Functional Programming in Java, make code more concise, and are essential for using the Java Streams API efficiently!"


πŸ’‘ Pro Tip: "One interface, multiple implementationsβ€”that's the power of being flexible!" - Anonymous


← Back: RegEx & Threads | Next: Reference β†’