Sample usage of Lambda Expression with Runnable interface- Functional Programming in JAVA 8- Part 3

Java

Sample usage of Lambda Expression with Runnable interface- Functional Programming in JAVA 8- Part 3

Before reading this post kindly visit from part 1 of this post to understand lambda expression.

http://jkoder.com/understanding-java-8-lambda-expression-functional-programming-in-java-8-part-1/

There is no Function Type in JAVA for lambda expression types, JAVA designers reused the concept of Interface Type that is already available in JAVA. There may be several reasons why the JAVA language designers decided to use an interface as a type for lambda expression instead of a new Function Type, but the most important reason which I think is backward compatibility. Advantage of lambdas is we can use it in place of all those anonymous inner classes & all the methods which accepts the interface(with just one condition, there must be only one abstract method).

Let’s take the example of Runnable interface. Everybody knows how to create a and start a Thread in JAVA using Thread class and Runnable interface. In order to create a new Thread, you would have to create a new instance of Runnable & use that instance to create a new Thread.

Guess what! Since Runnable is an interface with just one abstract method, it works well with lambdas. You can use the lambdas in order to create a new Runnable.

public class RunnableExample {

	public static void main(String[] args) {
		Thread myThread=new Thread(new Runnable() {
			@Override
			public void run() {
				System.out.println("Printed inside Runnable");
			}
		});
		myThread.start();
	}
}

So in the above, rather than creating a new class in a separate file that implements Runnable interface, we just did an anonymous inner class. Now let’s rewrite the above code using the lambdas.

public class RunnableExample {

	public static void main(String[] args) {
		Runnable myRunnableLambda=()->System.out.println("Printed inside lambda Runnable");
		Thread myThreadLambda=new Thread(myRunnableLambda);
		myRunnableLambda.start();
	}
}

Take a comparison, it’s pretty much crisp and concise when using lambdas. Remember, this works because Runnable has a single method. If it had more than one method then you could not have written lambda expression of Runnable type. This is the magic of having the interface mechanism of declaring the lambdas, you get the huge benefit of backward compatibility. But the interface must have only one abstract method, this type of interface is called Functional Interface.

About Anoop Kumar Rai