How Lambda works in Java

Lambdas are a feature of the Java programming language that allows you to create anonymous functions, or functions without a name. They are often used to pass blocks of code as arguments to methods, or to define the implementation of an interface in a concise and easy-to-read way.

Here is a simple example of a lambda expression in Java:

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

This lambda expression takes two integer arguments, x and y, and returns the sum of x and y.

You can use lambda expressions wherever you would use a functional interface, which is an interface with a single abstract method. For example, the java.util.function.BiFunction interface has a single abstract method called apply, which takes two arguments and returns a result. You can use a lambda expression to implement this interface:

BiFunction<Integer, Integer, Integer> adder = (x, y) -> x + y;
int result = adder.apply(1, 2);  // returns 3

You can also use lambda expressions to define the implementation of a Runnable interface, which has a single abstract method called run that takes no arguments and returns void:

Runnable task = () -> System.out.println("Hello, World!");
task.run();  // prints "Hello, World!"

Lambdas can also have a block of code as their body, in which case you need to use curly braces to enclose the code:

BiFunction<Integer, Integer, Integer> adder = (x, y) -> {
  int sum = x + y;
  return sum;
};
int result = adder.apply(1, 2);  // returns 3

You can also use the return keyword explicitly in a lambda with a single statement:

BiFunction<Integer, Integer, Integer> adder = (x, y) -> return x + y;
int result = adder.apply(1, 2);  // returns 3