Java Lambda Expression

In Java, a lambda expression is a way to define a block of code that can be passed around as a parameter to a method or assigned to a variable. Lambda expressions are used to implement functional interfaces, which are interfaces with a single abstract method. The syntax for a lambda expression is as follows:

r‮e‬fer to:theitroad.com
(parameters) -> expression

or

(parameters) -> { statements; }

Here, parameters is the input parameters for the method, expression is a single expression that is evaluated to return a value, and statements is a block of statements that can contain multiple expressions and can be used to perform more complex operations.

Lambda expressions can also use the var keyword to define local variables, which can help to make the code more concise and readable. For example:

(var x, var y) -> x + y

This lambda expression takes two input parameters x and y and returns their sum.

Lambda expressions are commonly used in Java 8 and later versions to implement functional interfaces, such as the Comparator interface for sorting objects, the Runnable interface for creating threads, and the Consumer interface for iterating over collections.

Here is an example of using a lambda expression to sort a list of integers in ascending order:

List<Integer> numbers = Arrays.asList(5, 2, 8, 3, 1);

Collections.sort(numbers, (a, b) -> a.compareTo(b));

System.out.println(numbers); // output: [1, 2, 3, 5, 8]

In this example, we use a lambda expression to implement the Comparator interface and define the sorting order for the Collections.sort() method. The lambda expression takes two input parameters a and b and returns the result of the compareTo() method, which is used to compare the two values. The System.out.println() statement outputs the sorted list of integers.