In general a lambda expression is an anonymous function, which means for some combination of inputs, there is a specific output. In the context of Java, a lambda expression is a kind of anonymous method with a more compact constructor syntax. Lambdas in Java are first class citizens, and can be passed as method parameters (as a Functional Interface).

Lambdas are also popular in languages like Go, Clojure, and Swift.

Lambda Expression Syntax

For those that have never worked with lambdas before, their appearance can seem strange. Especially for Java developers. Here are some major points to know about lambda expression syntax:

  • • Java lambda syntax is as follows: (parameters) -> {statements}
  • • Lambdas can have 0 or more parameters
  • • Lambda parameter types can be declared or inferred
  • • Lambdas without parameters are indicated by using empty parentheses ()
  • • If a lambda has only has 1 parameter, the parentheses () can be omitted
  • • The expression/body of a lambda function can contain 0 or more statements
  • • If a lambda expression contains a single statement, curly braces {} can be omitted
  • • If a lambda expression only contains a single statement and curly braces are omitted, the return keyword is not necessary, and the return type will match the result of the expression

Lambda Expression Examples

//no input parameters, return the number 100
() -> 100 

//no input parameters, return the number 100
() -> {return 100} 

//no input parameters, print "Hello World"
() -> { System.out.print("Hello"); System.out.print(" World!"); };

//one input parameter, evaluate n % 5 != 0 
n -> n % 5 != 0; 

//one input parameter, evaluate c == '?'
(char c) -> c == '?'; 

//two input parameters, evaluate x * y
(x, y) -> x * y; 

Do Lambda Expressions have a Type?

Unlike other languages with lambdas, Java lambdas expressions are a subclass of Object, and an instance of a functional interface (an interface with a single abstract method).

Functional interfaces can be referred to as lambda target types. In order for a lambda expression to be tied to a specific target type, it must have the same parameter and return types. This means that the same lambda expression can be tied to different target types, as long as the input parameters and return types match.

Leave a Reply

What are Lambdas in Java?