A lambda expression is an anonymous method. This anonymous method is not executed on its own. Instead, it is used to implement a method defined by a functional interface. A functional interface is an interface that contains one and only one abstract method which typically represents a single action.
These are characteristics of a lambda expression:
(String a, String b) -> a+" "+b; // same as (a, b) -> a+" "+b;
a -> a; // same as (a) -> a;
a -> a; // same as a -> {return a;};
public class LambdaTest { interface Operator { int operation(int a, int b); } public int operate(int a, int b, Operator op) { return op.operation(a, b); } public static void main(String args[]) { Operator add = (int x, int y) -> x + y; LambdaTest test = new LambdaTest(); System.out.println("Addition is " + test.operate(6, 3, add)); } }
Lambda expressions are used primarily to define inline implementation of a functional interface.
Using lambda expression, you can refer to any final variable or effectively final variable (which is assigned only once). Lambda expression throws a compilation error, if a variable is assigned a value the second time.
@FunctionalInterface annotation
@FunctionalInterface annotation is used to ensure that the functional interface can’t have more than one abstract method. In case more than one abstract methods are present, the compiler flags an ‘Unexpected @FunctionalInterface annotation’ message. However, it is not mandatory to use this annotation.
@FunctionalInterface public interface Operator { int operation(int a, int b); // can have static methods static String sayHi(String name) { return name; } }
Very often, lambda expressions just call methods which are already implemented elsewhere. You can use method references. This is not always shorter, but it makes the code more readable.
a -> a.toLowerCase(); // same as String::toLowerCase;
Benefits of using Lambda expression
Integer[] numbers = {2, 54, 20, 1}; Arrays.sort(numbers, new Comparator<Integer>() { @Override public int compare(Integer a, Integer b) { return a - b; } }); System.out.println(Arrays.toString(numbers));
How about this version which is much cleaner and more readable.
Integer[] numbers = {2, 54, 20, 1}; Arrays.sort(numbers, (a, b) -> a-b); System.out.println(Arrays.toString(numbers));