Introduction
Lambda expressions are blocks of core that can be passed as argument of a function. In Java, precisely, they are similar (but not equal) to the anonymous classes. Java 8 is needed to use them.
Interfaces
In order to use lambdas with interfaces we need functional interfaces (with only one method).
Create a functional interface:
package com.luisgomezcaballero.lambdas; interface MyInterface { void myInterfaceMethod(); }
Now another class that implements it:
package com.luisgomezcaballero.lambdas; class MyImplementation implements MyInterface { @Override public void myInterfaceMethod() { System.out.println("myImplementationMessage"); } }
And now a service that uses that implementation:
package com.luisgomezcaballero.lambdas; class MyService { public void myServiceMethod(MyImplementation myImplementation) { myImplementation.myInterfaceMethod(); } }
Without lambda expressions:
MyImplementation myImplementation = new MyImplementation(); myImplementation.myInterfaceMethod();
With lambda expressions:
MyInterface myLambdaFunction = () -> System.out.println("myLambdaMessage"); myLambdaFunction.myInterfaceMethod();
By executing one or the other code the correspondent message will be printed on the console.
Threads
Lambda expressions can be used with threads too.
Normally Thread has been used with the Runnable interface this way:
Thread myNormalThread = new Thread(new Runnable() { @Override public void run() { System.out.println("myNormalThreadMessage"); } }); myNormalThread.run();
But we can be done easier using a lambda expression:
Thread myLambdaThread = new Thread(() -> System.out.println("myLambdaThreadMessage")); myLambdaThread.run();
Again, a different message will be printed on the console using one code block or the other.
Repository
The code of this project which has been used to demonstrate the use of lambda expressions can be located at https://github.com/luisgomezcaballero/lambdas-demo.
So, what do you think ?