Lambda expressions before saying, first tell us about the function interface
Functional Interface
Is the only defines an interface of abstract methods, we can use annotations @Functionallnterface, strong constraints to the interface as a function of this interface. As Runnable, Callable, Comparator interfaces.
Java interface built four functions: Consumer <T>, Supplier < T>, Function <T, R>, Predicate <T>.
Lambda expressions is designed to achieve expression of these functional interfaces.
@FunctionalInterface public interface Runnable { public abstract void run(); }
For example to Runnbale thread
Runnable runnable = new Runnable() { @Override public void run() { System.out.println("hello lambda!"); } }; new Thread(runnable).start();
Lambda can be modified with the expression:
Runnable runnable = ()->{ System.out.println("hello lambda!"); }; new Thread(runnable).start();
Wherein the list of parameters: the parameter list of a method consistent with the requirements of the interface.
Lambda Feature Summary
- Parameter Type list can not write directly are ignored. (Note that a parameter type, the parameter is not because because the JVM compiler infer the context data type )
- If only one parameter, the parentheses can be omitted
- If there is only a method body statements, you can omit the braces off
- If there is only one statement, and he is the return statement, then you can directly omit return keyword
Examples
A syntax: no parameters and returns no value type
public void test() { Runnable runnable = new Runnable() { @Override public void run() { System.out.println("Hello Lambda!"); } }; runnable.run(); } /** * () -> System.out.println("Hello Lambda!"); * / Public void Test () { // "->" is only a left parenthesis, indicating no parameter Lambda is the right (equivalent anonymous inner classes which implements the method, i.e., a category of the available interface) Runnable = the Runnable () -> the System. OUT .println ( "the Lambda the Hello! " ); runnable.run(); }
Syntax II: a parameter and return type None
/** * (x) -> System.out.println(x) * / Public void Test () { // method parameter e represents the implemented interface Consumer <String> Consumer = (e) -> the System. OUT .println ( " the Hello " + e); consumer.accept("Lambda"); } /** X * -> System.out.println (X)
* if a parameter "()" can be omitted * / public void Test () { // method parameter e represents the interface implemented Consumer <String> consumer = E-> the System. OUT .println ( "the Hello " + E); consumer.accept("Lamdba"); }
Syntax three: two or more parameters and return values, and the body more than one statement Lambda
public void Test4 () { // the Lambda body, a plurality of statements to use braces Comparator <Integer> COM = (X, Y) -> { . The System OUT .println ( " Functional Interface " ); return Integer.compare (X, Y); }; int compare = com.compare(100, 244); System.out.println(compare); }