What are lambda expressions?

Category : Java | Sub Category : Java8 Features | By Prasad Bonam Last updated: 2023-11-13 04:10:25 Viewed : 288

Lambda expressions are a powerful feature introduced in Java 8 that provides a concise way to represent anonymous functions or, more precisely, instances of functional interfaces. A lambda expression allows you to express instances of single-method interfaces (functional interfaces) more concisely and with less boilerplate code.

The basic syntax of a lambda expression is as follows:

(parameters) -> expression


(parameters) -> { statements; }

Here, parameters represent the input parameters of the functional interfaces single abstract method, and expression or { statements; } represents the body of that method.

Lets look at a simple example to illustrate the concept. Suppose you have a functional interface MyFunctionalInterface with a single method:

@FunctionalInterface interface MyFunctionalInterface { void myMethod(int x); }

You can create an instance of this interface using a lambda expression as follows:

MyFunctionalInterface myFunc = (x) -> System.out.println("Value is: " + x);

In this example, the lambda expression (x) -> System.out.println("Value is: " + x) represents the implementation of the myMethod from the MyFunctionalInterface. The x is the parameter, and the expression System.out.println("Value is: " + x) is the body of the method.

You can then call this method on the lambda expression as if it were an instance of the interface:


This would output:

Value is: 10

Lambda expressions are particularly useful when working with functional interfaces, such as those used with the Stream API, where concise and expressive code is often desirable. They help reduce verbosity and make the code more readable and maintainable.

Related Articles

Leave a Comment: