A Lambda Expression is a representation of an anonymous function which can be passed around as a parameter thus achieving behavior parameterization. A lambda consists of a list of parameters, a body, a return type and a list of exceptions which can be thrown. I.e. it is very much a function, just anonymous.
An instance of a lambda can be assigned to any functional interface
whose single abstract method’s definition matches the definition of the lambda. In fact, a lambda is a less verbose way of defining an instance of an interface provided the interface is functional. Since, the definition of a lambda can match the definition of multiple functional interfaces, hence, a lambda instance can be assigned to any of these matching interfaces.
The reason i picked this topic was because it was something new i have seen in the java language. Also wanted to know more about it and see if i can utilized it on some of my java programming language.
Examples of lambda expression.
First of all. Comparing java 7 to java 8.
public interface StateChangeListener {
public void onStateChange(State oldState, State newState);
}
In java 7 we implement this interface in order to listen for state changes. You do this
public class StateOwner {
public void addStateListener(StateChangeListener listener) { … }
}
But in java 8 you can add an event listener using a java lambda expression. like this.
StateOwner stateOwner = new StateOwner();
stateOwner.addStateListener(
(oldState, newState) -> System.out.println(“State changed”)
);
From this topic ( lambda expressions), i learned that previous java or java 7, if i wanted a block of code to be executed, we need to create an object and pass the object around. From Java 8, lambda expressions enable us to treat functionality as method argument and pass a block of code around. Lambda expressions in Java 8 are very powerful and therefore very compelling. For me, lambda expressions is way much better, convenient and very easy.
link to the resource : http://tutorials.jenkov.com/java/lambda-expressions.html
From the blog CS@worcester – Site Title by Derek Odame and used with permission of the author. All other rights reserved by the author.