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.
}
}
π 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