Lambda expressions in Java represent “functions”, something that take a number of parameters and produce at most one return value.

This could be expressed with anonymous classes but lambda expressions offer a more concise syntax.

Syntax

Lambda expression consist of a parameter list, an “arrow” and a body.

The parameter list is enclosed in round brackets. Types are optional. When the expression has exactly one parameter, the brackets can be omitted.

The body can either be an expression (that returns a value) or a block. A block is a sequence of statements, enclosed in curly braces.

Lambda expressions and types

In the Java type system, lambda expressions are instances of “functional interfaces”. A functional interface is an interface with exactly one abstract method.

Functional interfaces in java.util.function

The package java.util.function in the JDK contains a number of functional interfaces:

  • Function<T,U>  represents a function with one parameter of type T and return type U
  • Consumer<T>  represents a function with one parameter of type T and return type void
  • Supplier<T>  represents a function with no parameter and return type T
  • Predicate<T>  represents a function with one parameter of type T and return type boolean

Plus, variants with “Bi” prefix exists that have two parameters, like BiPredicate . More variants exists for using primitive types like DoubleToIntFunction .

User defined function interfaces

Any interface with exactly one abstract method can be used as type of a lambda expression. You mark this interface with @FunctionInterface .

Benefits

For me, the benefits of lambda expression are

  • concise syntax for anonymous classes that represent functional code
  • improved readability
  • encouragement of a more functional programming style

Comments are closed.