instagram

Java 8 Lambda Expression

Lambda expression is most popular topic in java 8. Lambda expression works with functional interface. Read more about functional interface here.

Using Lambda expression is very easy to provide an implementation of the interface.

Let’s start with one functional interface.

@FunctionalInterface
public interface Car {
	
	public void printColor();
	
	
}
Without Lambda

Below code contains normal implementation of Car interface.

public class Main {

	
	public static void main(String[] args) {
		
		
		Car blueCar = new Car() {
			
			@Override
			public void printColor() {
				System.out.println("BLUE");
			}
		};
		
		blueCar.printColor();

	}

}
Using Lambda

There is only one line of code.

public class Main {

	
	public static void main(String[] args) {
		
		
		Car blueCar = () -> {System.out.println("BLUE");};
		blueCar.printColor();

	}

}

It is very very easy to implement functional interface using Lambda expression.
let’s look at other examples.

Method with arguments

Again Car interface but this time method have two arguments.

@FunctionalInterface
public interface Car {
	
	public void printColor(int carId,String color);
	
	
}

Implementing it using Lambda.

public class Main {

	
	public static void main(String[] args) {
		
		
		Car blueCar = (_id,color) -> {System.out.println("Car Id :"+_id+" & Color :"+color);};
		blueCar.printColor(378,"White");

	}

}
Using local variables with Lambda

public class Main {

	
	
	
	public static void main(String[] args) {
		
		String carName = "BMW";
		String country = "India";
		 
		Car blueCar = (_id,color) -> {System.out.println("Car Id :"+_id+" | Color :"+color+" | Car Name :"+carName+" | Country :"+country);};
		
		blueCar.printColor(378,"White");

	}

}
Using Lambda with Thread

We can use Lambda expression to provide implementation of Runnable interface.

public class Main {
	
	
	public static void main(String[] args) {
		
	    Thread t = new Thread( ()-> { System.out.println("This is impl of run method "); } );

	}

}
Share