Lambda expression
Lambda expressions, also known as closures, are the most important new feature driving the release of Java 8.
Lambda allows functions to be passed as parameters to a method.
Using Lambda expressions can make your code more concise and compact.
grammar
The syntax format of the lambda expression is as follows:
(parameters) -> expression
(parameters) ->{ statements; }
The following are important features of lambda expressions:
- Optional type declaration: There is no need to declare parameter types, and the compiler can universally identify parameter values.
- Optional parameter parentheses: One parameter does not need to define parentheses, but multiple parameters need to define parentheses.
- Optional braces: If the body contains a statement, braces are not required.
- Optional return keyword: If the body has only one return value from an expression, the compiler automatically returns the value, and the braces need to specify that the explicit expression returns a numeric value.
Lambda expression instance
A simple example of a Lambda expression:
// 1. No parameters required,Return value is 5 () -> 5 // 2. Receive a parameter(Number type),Returns its value twice x -> 2 * x // 3. Accept 2 Parameters(number),And return their difference (x, y) -> x – y // 4. Receive 2 int Type integer,Return their sum (int x, int y) -> x + y // 5. Accept one string object,And print in console,No value returned(It looks like you're back void) (String s) -> System.out.print(s)
Enter the following code in the Java8Tester.java file:
public class Java8Tester { public static void main(String args[]){ Java8Tester tester = new Java8Tester(); // Type declaration MathOperation addition = (int a, int b) -> a + b; // Do not use type declaration MathOperation subtraction = (a, b) -> a - b; // Return statements in braces MathOperation multiplication = (int a, int b) -> { return a * b; }; // No braces and return statements MathOperation division = (int a, int b) -> a / b; System.out.println("10 + 5 = " + tester.operate(10, 5, addition)); System.out.println("10 - 5 = " + tester.operate(10, 5, subtraction)); System.out.println("10 x 5 = " + tester.operate(10, 5, multiplication)); System.out.println("10 / 5 = " + tester.operate(10, 5, division)); // No parentheses GreetingService greetService1 = message -> System.out.println("Hello " + message); // Use parentheses GreetingService greetService2 = (message) -> System.out.println("Hello " + message); greetService1.sayMessage("Nowcoder"); greetService2.sayMessage("Google"); } interface MathOperation { int operation(int a, int b); } interface GreetingService { void sayMessage(String message); } private int operate(int a, int b, MathOperation mathOperation){ return mathOperation.operation(a, b); } }
Execute the above script, and the output is:
$ javac Java8Tester.java $ java Java8Tester 10 + 5 = 15 10 - 5 = 5 10 x 5 = 50 10 / 5 = 2 Hello Nowcoder Hello Google
There are two things to note when using Lambda expressions:
- Lambda expressions are primarily used to define method type interfaces for inline execution, such as a simple method interface.In the example above, we use various types of Lambda expressions to define the methods of the MathOperation interface.Then we define the execution of sayMessage.
- Lambda expressions eliminate the hassle of using anonymous methods and give Java simple but powerful functional programming capabilities.
Variable Scope
A lambda expression can only refer to an outer local variable marked final, which means that a local variable defined outside the domain cannot be modified inside the lambda, otherwise an error will be compiled.
Enter the following code in the Java8Tester.java file:
public class Java8Tester { final static String salutation = "Hello! "; public static void main(String args[]){ GreetingService greetService1 = message -> System.out.println(salutation + message); greetService1.sayMessage("Nowcoder"); } interface GreetingService { void sayMessage(String message); } }
Execute the above script, and the output is:
$ javac Java8Tester.java
$ java Java8Tester
Hello! Nowcoder
We can also access the outer local variables directly in the lambda expression:
public class Java8Tester { public static void main(String args[]) { final int num = 1; Converter<Integer, String> s = (param) -> System.out.println(String.valueOf(param + num)); s.convert(2); // Output result is 3 } public interface Converter<T1, T2> { void convert(int i); } }
Local variables of lambda expressions may not be declared final, but must not be modified by subsequent code (that is, implicit final semantics)
int num = 1; Converter<Integer, String> s = (param) -> System.out.println(String.valueOf(param + num)); s.convert(2); num = 5; //Error message: Local variable num defined in an enclosing scope must be final or effectively final
It is not allowed to declare a parameter or local variable with the same name as a local variable in a Lambda expression.
String first = ""; Comparator<String> comparator = (first, second) -> Integer.compare(first.length(), second.length()); //Compilation error
A function can be used either as a parameter or as a return value. Take a look at the following example
//This is normal Collections Writing of sorting, rewriting interface methods public void test1(){ List<String> list =Arrays.asList("aaa","fsa","ser","eere"); Collections.sort(list, new Comparator<String>() { @Override public int compare(String o1, String o2) { return o2.compareTo(o1); } }); for (String string : list) { System.out.println(string); } } //This is of parametric type Lambda Writing of public void testLamda1(){ List<String> list =Arrays.asList("aaa","fsa","ser","eere"); Collections.sort(list, (Comparator<? super String>) (String a,String b)-> {return b.compareTo(a); }); for (String string : list) { System.out.println(string); } } //This is parameterized lambda Writing of public void testLamda2(){ List<String> list =Arrays.asList("aaa","fsa","ser","eere"); Collections.sort(list, (a,b)->b.compareTo(a)); for (String string : list) { System.out.println(string); } }