How to define lambda expression in Java?

How to define lambda expression in Java?

In Java, a lambda expression is a concise way to represent a function as an object. It allows you to define a function inline, without the need to create a separate class or method.

To define a lambda expression in Java, you can use the following syntax:

r‮ refe‬to:lautturi.com
(parameters) -> { function body }

Here, parameters is a list of parameters that the lambda expression takes, and function body is the code that is executed when the lambda expression is called.

For example, consider the following lambda expression that adds two integers and returns the result:

(int x, int y) -> { return x + y; }

This lambda expression takes two integers, x and y, and returns their sum.

You can assign the lambda expression to a variable of a functional interface type. A functional interface is an interface that has a single abstract method. For example, the java.util.function.BiFunction interface is a functional interface that has a single abstract method that takes two arguments and returns a result.

Here's an example of how to assign the lambda expression to a BiFunction variable:

BiFunction<Integer, Integer, Integer> adder = (int x, int y) -> { return x + y; };

You can then call the lambda expression by using the functional interface's apply method, like this:

int result = adder.apply(3, 4);  // result will be 7

If the lambda expression has a single statement in its body, you can omit the curly braces and the return statement. For example, the following lambda expression is equivalent to the one above:

BiFunction<Integer, Integer, Integer> adder = (int x, int y) -> x + y;

If the lambda expression has a single parameter, you can omit the parentheses around the parameter. For example, the following lambda expression returns the square of its parameter:

sqr = x -> x*x;

The lambda expression also can be written in any of the following forms:

sqr = (double x) -> { return x*x; }; // The full lambda expression syntax!
sqr = (x) -> { return x*x; };
sqr = x -> { return x*x; };
sqr = x -> x*x;
sqr = (double fred) -> fred*fred;
sqr = (z) -> z*z;
Created Time:2017-11-01 20:42:47  Author:lautturi