In Java 8, the introduction of lambda expressions and functional interfaces revolutionized the way we write code. Lambda expressions allow us to write concise and readable code while functional interfaces provide the necessary type information for lambda expressions. In this article, we’ll dive into lambdas and functional interfaces and explore how they work in Java.
Lambdas
Lambda expressions are a way to express a function in a more concise and readable way. They allow us to define anonymous functions, which are functions that don’t have a name, and pass them around as values. A lambda expression consists of three parts: a set of parameters, an arrow ->
, and a body.
Here’s an example of a lambda expression that takes two integers and returns their sum:
(int a, int b) -> a + b
The above lambda expression takes two int
parameters a
and b
, and returns their sum. The ->
operator separates the parameter list from the body of the lambda expression. The body can be a single expression, as in the example above, or a block of code enclosed in curly braces {}
.
Lambdas are often used with functional interfaces, which provide the necessary type information for the lambda expression.
Functional Interfaces
A functional interface is an interface that has exactly one abstract method. In other words, it’s an interface that is designed to be used as a functional type. In Java 8, functional interfaces are annotated with the @FunctionalInterface
annotation, which ensures that the interface has only one abstract method.
Here’s an example of a functional interface:
@FunctionalInterface
interface MyFunctionalInterface {
int apply(int a, int b);
}
The above functional interface has one abstract method called apply
, which takes two int
parameters and returns an int
. It can be used with a lambda expression to define a function that takes two int
parameters and returns their sum:
MyFunctionalInterface add = (a, b) -> a + b;
int result = add.apply(3, 5); // result is 8
In the above code, we define a lambda expression that takes two int
parameters and returns their sum. We then create an instance of the functional interface MyFunctionalInterface
using the lambda expression, and call its apply
method to apply the lambda expression to the arguments (3, 5)
.
Functional interfaces are used extensively in Java 8 APIs, such as the java.util.function
package, which provides a set of functional interfaces for common use cases, such as predicates, consumers, and suppliers.
Conclusion
In this article, we’ve explored lambdas and functional interfaces in Java 8. We’ve seen how lambdas allow us to write concise and readable code, and how functional interfaces provide the necessary type information for lambdas. We’ve also seen how functional interfaces are used in Java 8 APIs, such as the java.util.function
package. By using lambdas and functional interfaces, we can write more expressive and concise code, making our programs more maintainable and easier to understand.