Home > database >  Lambda expressions basic grammar
Lambda expressions basic grammar

Time:10-04

Lambda is an anonymous function, we can the lambda understood as a pass code, the Java language expression ability get promoted

A. The foundation of the lambda syntax java8 introduced a new operator "- & gt;" This operator called arrow operator or lambda operator (the implementation of the interface?
Arrow operator lambda expressions can be divided into two parts:
Left: the lambda expressions argument list
Right: lambda expressions need to perform the function of the lambda body

A syntax format: no parameters, no return value
() - & gt; System. Out.println (" hello lambda ") : (anonymous inner class) Runnable r=new Runnable () {public void the run () {System. Out. Println (" hello lambda ")}}
Using the lambda expressions:
A Runnable r=() - & gt; System. Out.println (" hello lambda ")


Example: local anonymous inner class)
int num=0;//jdk1.7 before, must be the final modification
Default as final jdk1.8
A Runnable r=new Runnable () {public void the run () {System. Out. Println (" hello lambda "+ num)}}
Using the lambda expressions:

A Runnable r=() - & gt; System. Out.println (" hello lambda "+ num)
R.r UN ();


Syntax format 2: there is a parameter, there is no return value (x) - & gt; System. The out. Println (x);

Consumer Con=(x) - & gt; System. The out. Println (x); Con. Accpet (" hahah ");


Syntax format 3: if only one parameter, has no return value lambda expressions left parentheses can not write a
X-ray & gt; System. Out.println (x)

Syntax format 4: there are two or more parameters, return values and lambda have multiple statements in

Comparator Com=(x, y) - & gt; {System. Out. Println (" functional interface ");
Return to Integer.com pare said (x, y); }

Syntax format 5: if the lambda body only one statement return and braces can omit don't write (and grammar) comparison between the four Comparator Com=(x, y) - & gt; Integer.com pare said (x, y);

Syntax format six: lambda expressions and you don't write the data type of the argument list may be omitted because the JVM the compiler can infer from context data types, namely "type inference
"Type inference: String [] STR={" aaa ", "BBB", "CCC"} List List=new ArrayList<> (a);
Comparator Com=(Integer x, Integer y) - & gt; Integer.com pare said (x, y); (here compared to grammar five)


Conclusion: around in a province on the left side of the inference type bracket on the right side only one statement return also can omit


2. Lambda expressions need the support of "functional interface" functional interface: the interface is only an abstract method in the interface, called functional interface, you can use the annotation @ FunctionInterface modification and then check for functional interface

CodePudding user response:

Thanks for sharing, it is recommended that the blog

CodePudding user response:

Personal summary, thank you for your advice
  • Related