So far, it's not easy to pass a piece of code to other code in Java. You can't pass blocks of code around. Because Java is an object-oriented language, you have to build an object that belongs to a class, and one of its methods contains the required code.
Lambda expressions help us solve this problem and can pass code blocks directly! The format of a lambda expression in Java: parameters, Arrows (-), and an expression. Example:
(String first,string second), Integer.compare (First.length (), Second.length ())
If the code that is responsible for the calculation cannot be represented by an expression, you can write it in the same way: by wrapping the code with {} and explicitly using the return statement, for example:
(String first,string Second), {if (First.length () < Second.length ()) return-1; else if (first.length () > Second.length ()) return 1;}
If the lambda expression has no arguments, you can still supply a pair of empty parentheses, just like a method with no parameters:
(), {for (int i=0; i<1000;i++) Dowlrk ();}
If the parameter types of a lambda expression can be inferred, then the type of them can be omitted, for example:
Comparator<string> comp = (first,second), Integer.compare (First.length (), second.length ());
Here, the compiler infers that first and second must be strings, because the lambda expression is assigned to a string comparer. If a method contains only one parameter, and the type of the argument can be deduced, you can even omit the parentheses:
Eventhandler<actionevent> listener = event, System.out.println ("Thanks for clicking!");
Note: You can add annotations or final modifiers to the parameters of a lambda expression as you would for a method parameter, as follows:
(final String name) .... (@NonNull String name) ...
It is never necessary to perform a return type for a lambda expression, which is always inferred from the context. For example, an expression:
(String first,string second), Integer.compare (First.length (), Second.length ())
can be used in contexts where the expected result type is int.
Note: In a lambda expression, it is not legal to return a value in only some branches (no other branch has a return value), for example:
Non-law (int x), {if (x >= 0) return 1;}
Java8 lambda expression (lambda expression syntax)