What are lambda expressions in Java, and how are they used?
What are lambda expressions in Java, and how are they used?
612
19-Jul-2024
Updated on 19-Jul-2024
Ashutosh Kumar Verma
19-Jul-2024Lambda Expressions in Java
Lambda expressions in Java are a shorthand way of representing anonymous functions: functions without a name that can be executed later by passing them around. They are essentially a way of defining a method without formally declaring it in a class.
The syntax for a lambda expression
The simple lambda expressions contain a single parameter and expression,
If you need to use more than one parameter, wrap them into a parentheses ().
Here is a simple example where a lambda expression is used to define a function that calculates the square of a number,
Function without lambda expression
Function with lambda expression
Output-
Usage
Lambda expressions are mainly used in functional networks, which are exactly one-way abstract interfaces. They provide a concise way to implement a method defined by a user interface.
For example, in Java, the
java.util.function
package contains many function interfaces such asPredicate
,Consumer
, andFunction
, which can be effectively implemented in lambda expressions.Benefits
Conciseness- Lambda expressions reduce the amount of boilerplate code that comes with anonymous classes.
Readability- The code is made readable by focusing on what needs to be done rather than how.
Functional Programming- Lambda expressions enable a highly efficient functional form in Java, facilitating tasks such as mapping, filtering, and reducing collections.
Limitations
There are some restrictions on lambda expressions:
Can only be used in functional interfaces.
Cannot have
return
statements without curly braces {} around the body.Cannot contain
void
as a return type (useConsumer
for the void method).When to Use
Lambda expressions are especially useful in situations where you need to pass a statement (to some extent) as an argument to a method or do it asynchronously. It is widely used in streams, threads, event handling, and other functional programming constructs.
Also, Read: What are lambda expressions, and how are they used in LINQ queries?