Lambda in Java
If like me, you have found Lambda to seem a little too much like magic, let me see if I can help you connect the dots like I did!
Lambda’s allow programmers to implement an interface that contains one abstract method, without having to write the full class. They consist of:
- a parameter list,
- the arrow token, and
- a return value based on the body of the code statements.
So, here are the key points for me:
- We are writing the body of a method
- The method we are writing is the abstract method of an interface
- The compiler knows which method, since the interface has only ONE abstract method
- The number and type of parameters is defined by the abstract method in the interface
Consider the following Computations interface:
public interface Computations {
public double operation(double first, double second);
}
We could create classes AdditionComputation and MultiplyComputation as well as several others, such as:
public class AdditionComputation implements Computations {
@Override
public double operation(double first, double second) {
return first + second;
}
}
and similarly for MultiplyComputation:
public class MultiplyComputation implements Computations {
@Override
public double operation(double first, double second) {
return first * second;
}
}
To use these classes, we might write the following:
public class LambdaTester {
public static void main(String[] args) {
AdditionComputation add = new AdditionComputation();
MultiplyComputation mult = new MultiplyComputation();
IO.println(add.operation(5.3, 2.3));
IO.println(mult.operation(5, 3));
}
}
Every time we wanted to provide unique functionality for the operation method in Computations, we would need to:
- create a class that implements
Computations
- create an instance of this class
- call the method
operation
With lambdas, we can create an instance of Computations that can be used to call the operation method and provide the functionality as part of declaring and creating that instance.
Consider implementing an operation method to subtract two values. We can create an instance, for example called subt, and use lambda to provide the implementation of the operation method as follows:
Computations subt = (f, s) -> f - s;
IO.println(subt.operation(3,2));
Another example of using lambda is the forEach method of the ArrayList class. This method takes a Consumer object as a parameter. Consumer is an interface that has an accept method that needs to be implemented. The accept method performs an operation on the given argument. The following example passes the implementation of the method accept as an argument to the forEach method. For example, names is an ArrayList of String values:
names.forEach( (n) -> {
if (n.length() > 4) {
IO.println(n);
}
} );
If you shared in my confusion of lambda’s, I hope this has helped make them more understandable and less magical.
Resources