Lambda Expression in Java

Lochana Edirisinghe
2 min readMar 27, 2020

Hello everyone,

Today I am going to talk about Lambda Expression(since JDK 1.8) of Java

The Lambda expression is used to provide the implementation of a functional interface. This is a replacement for the Anonymous inner class. The functional interface means it has only one abstract method. But it may has default methods.

Where the Lambda Expression is used?

Think if you want to implement a functional interface, then normally you have to create another class and implement it from the interface. And you have to override the abstract method. See the following example.

interface Vehicle {
public void park ();
}
class Car implements Vehicle {
public void park () {
System.out.println ("Car parking");
}
}
class Demo {
public static void main (String args []) {
Vehicle v1= new Car ();
v1.park ();
}
}

Using Lambda Expression, you don’t want to create the Car class separately. You can make it within the Demo program. Let’s see,

interface Vehicle{
public void park();
}
class Demo{
public static void main(String args[]){

Vehicle v1=()->{
public void park(){
System.out.println("Car parking");
}
};

v1.park();
}
}

Here actually compiler creates a class implemented by Vehicle interface and assigns it to the Vehicle reference.

If the override method has only one statement, then you can write only the method body without “public void park()”.

interface Vehicle{
public void park();
}
class Demo{
public static void main(String args[]){

Vehicle v1= ()->System.out.println("Car Parking");

v1.park();
}
}

And also if the method is a parameterized then,

interface Vehicle{
public void park(int x);
}
class Demo{
public static void main(String args[]){

Vehicle v1=(x)->System.out.println("Car Parking"+ x);

v1.park(x);
}
}

I hope you got some idea about the Lambda Expression. We will discuss about java interfaces in near future.

Thank you!!

--

--