Java 8 lambda sample details
- 2020-07-21 08:18:43
- OfStack
The expression is essentially an anonymous method. Let's look at this example:
public int add(int x, int y) {
return x + y;
}
The lambda expression looks like this:
(int x, int y) -> x + y;
Parameter types can also be omitted and the Java compiler will infer from the context:
(x, y) -> x + y; // Returns the sum of two Numbers
or
(x, y) -> { return x + y; } // Explicitly specifies the return value
As you can see, the lambda expression has three parts: an argument list, and the arrow (-) > ), and a block of expressions or statements.
The expression in this example has no arguments and no return value (equivalent to one method taking 0 arguments and returning void, which is a single implementation of run in Runnable) :
() -> { System.out.println("Hello Lambda!"); }
If there is only one argument and the type can be inferred by Java, the parentheses in the argument list can also be omitted:
c -> { return c.size(); }
public static void main(String[] args) {
Arrays.asList( "a", "b", "d" ).forEach( e -> {
System.out.print( e +"\n");
} );
System.out.print( "\n--------------------------" );
Arrays.asList( "a", "b", "d" ).sort( ( e1, e2 ) -> e1.compareTo( e2 ) );
/**
* So lambda expression has 3 Part: Parameter list, arrow ( -> ), and 1 A block of expressions or statements.
* The expression in this example has no arguments and no return value 1 Methods of acceptance 0 Parameter, return void In fact, it is Runnable In the run methods 1 ) :
* () -> { System.out.println("Hello Lambda!"); }
*/
Thread t2=new Thread(()->{
System.out.println("This is from an anonymous method (lambda exp).\n");
});
t2.start();
/**
* The iteration LIST
*/
List<String> listStr=new ArrayList<>();
listStr.add("sss");
listStr.add("1111");
listStr.forEach(e->{
if(e.equals("sss")){
System.out.print(e);
}
});
}