Lambda expression - nus-cs2030/2122-s1 GitHub Wiki
What are lambda expressions in java?
- lambda functions are similar to methods
- The difference is that they can be created in the methods body and arguments and they don't need a name
Advantages of lambda expressions
- we can assign them as values
- pass them in as arguments
- return lambda from methods
Syntax
- The simplest way to create a lambda expression which contain 1 parameter and an expression is
- parameter -> expression
eg. x -> x * x (will return you the square of the the argument) similar to
int square(int x) { return x * x; }
- If there is no parameter the syntax will be () -> expression
- If you have more than 1 parameter use parenthesis to contain them
(para1, para2) -> expression
- note within the parenthesis it can contain more than 2 parameter
- There are limitations to expressions
- They have to return a value immediately
- cannot create variables in it
- cannot have assignments
- no if else statements
- no for/while loops
To overcome this limitations we wrap the code using curly braces {}.
- (para1, para2) -> {code}
eg. (Integer i, Interger j) -> {return j-i}
- note within the code if the method return a value or object there must be a return statement