πΉ What is a Lambda Expression?
AΒ Lambda Expression in Java is a short block of code that takes in parameters and returns a value, used primarily to implement functional interfaces.
β Think of it as a way to write anonymous functions more cleanly.
π Syntax of Lambda
Examples:
π― Functional Interface Reminder
A Functional Interface has only one abstract method.
Example:
You can use a lambda to implement it:
β Real-World Usage
πΉ 1. Using Lambda with Threads
πΉ 2. Using Lambda with Collections
πΉ 3. Comparator Example
π¦ Common Functional Interfaces in java.util.function
Interface | Method Signature | Example Usage |
---|---|---|
Predicate<T> |
boolean test(T t) |
Filtering lists |
Function<T,R> |
R apply(T t) |
Mapping values |
Consumer<T> |
void accept(T t) |
Printing, logging |
Supplier<T> |
T get() |
Supplying default values |
π Benefits of Lambda Expressions
- More concise and readable code
- Enables functional programming
- Reduces boilerplate (e.g., anonymous inner classes)
- Great for stream and collection APIs
π§ Summary
Concept | Example |
---|---|
Basic Syntax | (a, b) -> a + b |
Functional Interface | One method interface (e.g., Runnable ) |
Use Case | Collections, threads, event handling |
Advantage | Concise, elegant, modern code |
Β
Β