To give a sort of example, we pass in the code to check if one string is shorter than the other. Here to calculate:
First.length ()-Second.length ()
What is first and second? They are all strings. Java is a strongly typed language, so we'll also specify their type:
(string First, string second) First.length ()-Second.length ()
A lambda expression is a block of code and a variable specification that must pass in the code.
You've seen a lambda expression form in Java: arguments, Arrows (-), and an expression. If the code is to complete a calculation that cannot be placed in an expression, you can put the code in {} Like a write method, and include an explicit return statement. For example:
(string First, string second), { ifreturn -1; Else if return 1; Else return 0; }
Even if the lambda expression has no arguments, you still need to provide the empty parentheses, just like a parameterless method:
() {for(int i=100; i>=0; i--) System.out.println (i);}
If you can deduce the parameter type of a lambda expression, you can omit its type. For example:
comparator<string> Comp //same as (String first,string second) First.length ()-second.length ();
Here, the compiler can deduce that first and second must be strings, because the lambda expression will be assigned to a string comparer.
If the method has only one parameter, and the type of the argument can be deduced, you can even omit the parentheses:
ActionListener listener = event, System.out.println (new Date ());
You do not need to specify the return type of a lambda expression. The return type of a lambda expression is always inferred from the context. For example, the following expression
(string First, string second), First.length ()-Second.length ()
can be used in contexts where the result of an int type is required.
The following Java code shows how to use a lambda expression in a comparer and an action listener
PackageLambda;Importjava.util.Arrays;Importjava.util.Date;ImportJavax.swing.JOptionPane;ImportJavax.swing.Timer; Public classLambdatest { Public Static voidMain (string[] args) {string[] planets=NewString[] {"Zhangsan", "Lisi", "Wangwu", "Zhaoliu", "Xiaoming", "Xiaohong", "Xiaofang", "Quzi" }; System.out.println (arrays.tostring (planets)); System.out.println ("Sort by dictionary order:"); Arrays.sort (planets); System.out.println (arrays.tostring (planets)); System.out.println ("Sort by Length:"); Arrays.sort (Planets, (first, second)First.length ()-second.length ()); System.out.println (arrays.tostring (planets)); Timer T=NewTimer (System.out.println, event, "The time is" +NewDate ())); T.start (); //Keep the program running until the user clicks "OK"Joptionpane.showmessagedialog (NULL, "Quit program?"); System.exit (0); }}
Run results
Syntax for lambda (λ) expressions in Java