Java Lambda Expression
Lambda expression provided implementation logic for functional interfaces (interfaces with only one abstract method ) which we will discuss soon.
lambda expression add the essence of functional programming in java . They are functional constructs without classes, which can be passed like objects and executed as required. They also make the modifires, return type and parameter types completely optional.
Syntax of Lambda Expression
(arguments) -> (body)
the syntax of lambda expressions is comprised of three parts:
- An argument list: The parameter list should be the same (in terms of number, type, and order of arguments) as that of the abstract method of the interface. For example:Syntax:() -> { System.out.println("No argument"); }OR(int argument1, String argument2) -> { System.out.println("Multiple arguments"); }Argument types can be eliminated, making them inferred types. i.e. (int argument) and (argument) are same.
Also, parenthesis () can be eliminated if there is only one argument. - The arrow(->) token
- The body:
(e1, e2) -> e1.getCountry().compareTo(e2.getCountry())
If the body contains a block of statements, curly braces should enclose them, and a return statement becomes mandatory when the block returns something.
(e1, e2) -> {
int value = e1.getCountry().compareTo(e2.getCountry());
return value;
}
Note: Inferred and declared types cannot be used together, i.e. (int x, y) -> x+y; is invalid.
Comments
Post a Comment