✅ What is a Lambda?
A lambda expression is a short block of code which takes in parameters and returns a value. It provides a clear and concise way to represent a functional interface.
🧪 Syntax:
(parameters) -> expression
// or
(parameters) -> { statements; }
✅ Examples:
Simple Runnable:
Runnable r = () -> System.out.println("Hello World");
Comparator:
Comparator<Employee> comp = (e1, e2) -> e1.getSalary() - e2.getSalary();
With Functional Interface:
@FunctionalInterface
interface MathOperation {
int operate(int a, int b);
}
MathOperation add = (a, b) -> a + b;
💡 Common Functional Interfaces (java.util.function):
|
Interface |
Method |
Use |
|
Predicate |
boolean test(T t) |
Used for filtering |
|
Function<T, R> |
R apply(T t) |
For mapping/transformation |
|
Consumer |
void accept(T t) |
For performing actions |
|
Supplier |
T get() |
For supplying results |
🔥 Method References (Lambda Shortcut)
|
Type |
Syntax |
Example |
|
Static method |
Class::method |
Math::abs |
|
Instance method |
object::method |
System.out::println |
|
Constructor |
Class::new |
ArrayList::new |