Lambda with Functional Interface in Java

Lambda is an expression. It was introduced in Java 8, it was changing the way of programming and its style. It’s very useful in the collection framework for iterate, filter and extract. By this you can define the inline implementation of functional interface. And it makes our java program as functional programming. It removes the usage of anonymous classes.

Advantages of lambda

  • Reduce the number of lines
  • Easily define functional interface
  • return statement and parenthesis are optional
  • Avoid the usage of anonymous classes.

functional Interface

The interface which is annotated with @FunctionalInterface is known as Functional interface. The best example of functional interface is Runnable, Callable, Consumer, Subscriber etc..

package com.samplecoder.lambda;

public class LambdaWithFunctionalInterface {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Runnable runnable1 = () -> {
			System.out.println("This is runnable interface 1");
		};
		
		
		Thread thread1 = new Thread(runnable1);
		
		Thread thread2 = new Thread(() -> {
			System.out.println("This is runnable interface 2");
		});
		
		thread1.start();
		
		thread2.start();
	}

}

Result

This is runnable interface 1
This is runnable interface 2