When we use lambda expressions, the most common operation is matching. However, there are many methods in the interface, and some friends will be confused when matching. What we can make clear is that lambda can match interfaces, so the specific matching instructions will be explained below, along with relevant example code.
1. Description
(1) Each lambda can match a given type through a specific interface. A so-called functional interface must have one and only one abstract method declaration. Each lambda expression corresponding to it must match the declaration of the abstract method. Since default methods are not abstract, feel free to add default methods to your functional interface.
(2) Any interface containing only one abstract method can be used for lambda expressions. In order for the defined interface to meet the requirements, the interface should be marked with @FunctionalInterface. If a second abstract method is defined in the interface, the compiler will notice this annotation and throw an exception.
2. Example
@FunctionalInterface interface Converter<F, T> { T convert(F from); } Converter<String, Integer> converter = (from) -> Integer.valueOf(from); Integer converted = converter.convert("123"); System.out.println(converted); // 123
Note that the program is also correct if the @FunctionalInterface annotation is not written.
The above is the method of matching Lambda expressions in Java interfaces. I believe that everyone has a new understanding of the use of Lambda expressions in this article. Please practice it as soon as possible after learning it.