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.
1 |
(String s1, String s2) -> s1 + "|" + s2 |
The parameter list is enclosed in round brackets. Types are optional. When the expression has exactly one parameter, the brackets can be omitted.
1 |
s -> s!=null && s.length>0 |
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.
1 |
n -> { if (n<10) System.out.println(n); } |
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 .
1 2 3 4 5 6 |
@FunctionalInterface interface SomeInterface { int someBehaviour(String a, String b); } SomeInterface geo = (x,y) -> x.length + y.length; |
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
Mentions