Lambda expressions enable functional programming in Java by allowing the creation of anonymous functions ( like we see in inner classes, annoymous inner class ). They provide a concise syntax for writing code that takes advantage of functional interfaces (interfaces with a single abstract method) and enables functional programming paradigms such as map, filter, and reduce operations.
Lambda expression is a shorthand way of writing an instance of a class that implements a functional interface.
Where to Use:
interface DogCourier{ public boolean test(Dog d);}class Dog{ int age; public Dog(int age) { this.age = age; } public int getAge() { return age; }}public class Test{ public static void main(String[] args) { Dog d = new Dog(10); /* old way of implement the interface method using Anonymous inner class DogCourier d = new DogCourier() { public boolean test(Dog d1) { return d1.getAge() > 9; } }; */ DogCourier dc = dog -> { return dog.getAge() > 10; }; // DogCourier d = (Dog newDC) -> return newDC.getAge() > 9; // compiler error boolean result = dc.test(d); System.out.println(result); }}falsexxxxxxxxxximport java.util.*;interface Add{ public int addTwoNumbers(int a, int b);}public class Calculator{ public static void main(String[] args) { /* Add sum = (a, b) -> { return a + b; }; */ // or //lambda expressions returns the results automatically Add sum = (a, b) -> a + b; System.out.println(sum.addTwoNumbers(10, 30)); }}40