Lambda basic grammar in java

Knowledge Point: Lambda basic grammar

  (A) using the Lambda expressions simplify anonymous inner classes

static void main public (String [] args) { 
// anonymous inner classes
Comparator <Integer> = new new COM Comparator <Integer> () {
@Override
public int Compare (O1 Integer, Integer O2) {
return Integer.compare (O1, O2);
}
};
// the Lambda expressions
Comparator <Integer> = COM1 (X1, X2) -> Integer.compare (X1, X2) ;
System.out.println (com1.compare (2,1));
}

the basic syntax (b) Lambda expressions
@ A: Lambda basic syntax 
/ * Java8 incorporated arrow operator "->" is divided into left and right portions of the lambda
left: parameter list Lambda expressions
on the right side: the function performed Lambda expression

syntax a: no parameter no return value
() -> System.out.println ( "Lambda body");

syntax II: there is a parameter, no return value
(x) -> System.out.println (x );

syntax III: left side of only one parameter, parentheses can be omitted
x -> System.out.println (x);

syntax four: two or more parameters, return values, and a plurality of body Lambda statement
Comparator <Integer> com = (X, Y) -> {
System.out.println ( "interface function");
return Integer.compare (X, Y);
};

syntax five: If the right Lambda body, only one statement, return and curly braces can be omitted
Comparator <Integer> com1 = (x , y) -> Integer.compare (x, y);

syntax six: the data type of the parameter list of Lambda expression can be omitted, compiled JVM will infer a context, the data type "type inference"
(X Integer, Integer Y) -> Integer.compare ();
* /

// two: Lambda expressions need to support "function interface" of
/ * function interface :
interface only an abstract interface method , called functional interface, you can use annotations @FunctionalInterface modifications
can check that the interface is not functional Interface
* /
Import org.junit.Test;
Import java.util.Comparator;
Import java.util.function.Consumer;
public class Test {
@Test
public void test1 () {
the Runnable R & lt new new = the Runnable () {
@Override
public void RUN () {
System.out.println (+ NUM "the Lambda body");
}
};
r.run ();

System.out.println ( "---------------- ----------------------- ");
the Runnable R1 = () -> System.out.println (" the Lambda body "NUM +);
r1.run ();

System.out.println("-------------------------------");
Consumer<String> con=(x)-> System.out.println(x);
con.accept("参数");

System.out.println("--------------------------------");

Comparator<Integer> com=(x,y)->{
System.out.println("函数式接口");
return Integer.compare(x,y);
};
System.out.println(com.compare(20,10));

System.out.println("------------------------------");
Comparator<Integer> com1=(x,y)->Integer.compare(x,y);
System.out.println(com1.compare(20,39));
}
}
 

Guess you like

Origin www.cnblogs.com/shuaifing/p/12158064.html