In Java, lambdas are a feature introduced in Java 8 that allows you to write concise and functional-style code by representing anonymous functions. They provide a way to pass behavior as a method argument, which can be especially useful when working with functional interfaces, which are interfaces with a single abstract method.
The syntax for a lambda expression consists of three parts: the parameter list, the arrow token “->”, and the body. The parameter list specifies the types and names of the parameters, the arrow token separates the parameter list from the body, and the body contains the code to be executed.
Here’s a basic example of a lambda expression that represents a function that adds two integers:
(int a, int b) -> a + b
This lambda expression takes two integer parameters a
and b
and returns their sum a + b
.
Lambdas are typically used with functional interfaces. A functional interface is an interface that has exactly one abstract method. Lambdas can be used to provide the implementation of that single method directly inline, without the need to define a separate class or method.
Lambdas are typically used in conjunction with functional interfaces. A functional interface is an interface that has exactly one abstract method. Java 8 introduced the java.util.function
package, which contains a set of built-in functional interfaces for common use cases. Here are a few examples:
Predicate<T>
: Represents a predicate (boolean-valued function) that takes an argument of type T
and returns a boolean.Consumer<T>
: Represents an operation that takes an argument of type T
and returns no result.Function<T, R>
: Represents a function that takes an argument of type T
and returns a result of type R
.Supplier<T>
: Represents a supplier of values of type T
.UnaryOperator<T>
: Represents an operation on a single operand of type T
and returns a result of type T
.BinaryOperator<T>
: Represents an operation on two operands of type T
and returns a result of type T
.