Skip to content
notkqXD edited this page Oct 13, 2021 · 1 revision

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

  1. we can assign them as values
  2. pass them in as arguments
  3. return lambda from methods

Syntax

  1. 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
  1. 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
  1. 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
Clone this wiki locally