I couldn't understand the lambda expression, so I've simplified it and understood the result.
First, an excerpt from Wikipedia about anonymous functions.
Anonymous function (English: anonymous function or nameless function) [1] in a programming language is a function defined without being named.
There are various methods for expressing anonymous functions, but in recent years [2] the mainstream is the lambda expression notation.
(Wikipedia (https://ja.wikipedia.org/wiki/anonymous function))
In other words, a lambda expression is a way to represent an anonymous function. ("->" Such a guy) → A lambda expression is a function that is defined without being named.
By the way, when writing in Java, it looks like this. (Excerpt from Wikipedia's anonymous function.)
sample.java
import java.util.function.*;
...
BiFunction<Integer, Integer, Integer> add = (x, y) -> x + y;
System.out.println(add.apply(2, 3));
↑ To explain with this example -"(X, y)" represents the argument of an anonymous function.
-"X + y" represents the processing of the function. (Although it is omitted in this example, it may be expressed as "{return x + y}". I think this is more method-like and easier to understand.)
What are you using anonymous functions for in the first place? That's why the functional interface comes out. Roughly speaking, it is an interface to which functions (see lambda expressions and methods) can be assigned.
For example, the interface BiFunction <T, U, R>
Type parameters: T --Type of first argument of function U --Type of second argument of function R-Function result type → An interface that allows you to assign a function that returns a return value with two arguments.
In other words, if you assign the anonymous function of the previous example to this interface and call the method (apply) defined in this interface, the processing of the anonymous function will be called. ↓ As for the result of this, since 2 and 3 are passed as arguments to apply, the result of 2 + 3 is output as standard.
sample2.java
BiFunction<Integer, Integer, Integer> add = (x, y) -> {return x + y;};
System.out.println(add.apply(2, 3));
Until now, I haven't thought about assigning functions to variables in Java, so I think it's difficult to understand. It seems to be a concept that comes up quite naturally when reading a JavaScript book.
Recommended Posts