First of all, Lambda expression is a new feature of Java8. It provides support for functional programming in Java programming and helps The simplicity of the code can replace most of the anonymous functions, especially for collection traversal and collection operations, which greatly simplifies the code.
The body of the Lambda expression:
Functional interface:
Note: Lambda expressions must be used with functional interfaces The so-called functional interface means that an interface with only one abstract method in the interface is a functional interface. We can customize it. JDK also has a large number of built-in functional interfaces.
1. The @FunctionalInterface annotation modifies the interface. Then this interface is a functional interface. It can only have one method. The following is a functional interface:
1 2 3 4 5 6 |
|
2. If @FunctionalInterface is not added **Note, if you write only one abstract method in the interface, it can also be considered as a functional interface:
1 2 3 |
|
This is also possible.
3. There is only one case where functional interfaces do not only have abstract methods, that is, they can inherit the methods of the Object class:
1 2 3 4 5 6 7 8 9 10 11 |
|
Student class:
1 2 3 4 5 6 |
|
Test class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
Output:
I am a student
Students eat
Student class:
1 2 3 4 5 |
|
Test class:
1 2 3 4 5 6 7 8 9 10 11 |
|
// Output: Students are eating meat
The method of creating multi-threads was introduced in the article on multi-threading (1). Here we use lambda to create threads:
1 2 3 4 5 6 7 8 9 10 11 |
|
We use lambda to operate operations and can save a lot of code:
Functional interface:
1 2 3 4 5 6 |
|
Test class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
|
Output:
15, 15, 5
Sometimes we don’t have to rewrite the interface methods to achieve specific implementation. If we have existing methods that can be implemented, we can also refer to existing methods through method references to make the methods in the interface specific. The advantage of this implementation is code reuse, such as the following:
Functional interface:
1 2 3 4 |
|
Test class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
|
Of course Lambda is also very convenient to operate collections, and you can save a lot of code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
The above is the detailed content of Java Lambda expression example analysis. For more information, please follow other related articles on the PHP Chinese website!