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.
(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.
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.
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 functional interfaces
Any interface with exactly one abstract method can be used as type of a lambda expression. You may mark this interface with @FunctionInterface
:
@FunctionalInterface
interface SomeInterface {
int someBehaviour(String a, String b);
}
SomeInterface foo = (x,y) -> x.length + y.length;
but it is not required.
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
Top comments (3)
Thanks for the post Erik.
What does the
@FunctionalInterface
do?I thought that: for any one-method interface, Java knows how to cast a lambda expression to an instance of the interface, even without this annotation.
orenovadia, your right: the annotation is not needed.
The
@FunctionalInterface
annotation enables the compiler to report an error if the interface is not a functional interface, i.e. it has exactly one abstract method. Beside that, it communicates the intend that the interface is a functional interface to the reader.Got it, thank you!