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);
}
}
false
xxxxxxxxxx
import java.util.*;
interface EvenOdd
{
public boolean isEven(int a);
}
public class EvenOddTest
{
public static void main(String[] args)
{
/*
EvenOdd result = (a) -> {
return a % 2 == 0;
};
*/
// (OR)
// lambda expressions returns the results automatically
EvenOdd result = a -> a % 2 == 0;
System.out.println(result.isEven(30));
System.out.println(result.isEven(11));
}
}
true
false