A lambda expression is a short way to write a method.
It is used mostly when you want to pass behavior (a block of code) as data.
Imagine a remote control. You can press a button to turn on the TV, turn on a fan, or start the AC.
You just change the behavior of the button.
Lambda expressions are like giving that behavior to a method.
(parameters) -> { code block }
Example:
(int a, int b) -> { return a + b; }
This means: "take two integers, and return their sum."
A functional interface is an interface with only one abstract method.
You can use lambda expressions with these interfaces.
@FunctionalInterface
interface Greeting {
void sayHello();
}
Now, let’s use a lambda expression:
Greeting g = () -> System.out.println("Hello!");
g.sayHello();
Simple, right?
Java gives us some ready-to-use functional interfaces.
Consumer<T>
: takes a value, returns nothing.Supplier<T>
: gives a value, takes nothing.Function<T, R>
: takes a value and returns something.Predicate<T>
: takes a value, returns true/false.Consumer<String> printer = (s) -> System.out.println(s);
printer.accept("Printing from Consumer!");
Supplier<Integer> randomSupplier = () -> 4; // Always gives 4 :)
System.out.println(randomSupplier.get());
Function<String, Integer> lengthFunction = (str) -> str.length();
System.out.println(lengthFunction.apply("Apple"));
Predicate<Integer> isEven = (x) -> x % 2 == 0;
System.out.println(isEven.test(10));
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.forEach(name -> System.out.println("Hi " + name));
Lambda expressions help you write short and clean code.
Functional interfaces work with them easily.
Practice with small examples, then try real projects!