Java 8 functional interface and functional interface examples
A functional interface is an interface that has only one abstract method, but can have multiple non abstract methods.
Functional interfaces can be implicitly converted to lambda expressions.
The functional interface can friendly support lambda with existing functions.
introduce
The functional interface is actually an abstract interface class. The existing functional interfaces before Java 8 include the following.
wait...
usage method
In fact, the interface class mentioned above only needs to be modified with functional interface annotation, and it has become a functional interface in Java. For example, the callable interface definition in JDK
It's that simple.
Now let's talk about the new function interface in Java 8. The following is its definition
It can be understood as a function pointer in C language (personal view).
In practice, the apply method is widely used. Compose / andthen is mostly used in scenarios where there are more than two function interfaces and the execution is sequential.
In the specific business code, I generally use it together with bifunctionon / supplier. Bifunction supports two parameters, and function only supports one parameter. Supplier can be used to store specific required values and obtain them through get.
example
Reference the code that works normally. This example mainly avoids the code bloated caused by multiple judgment conditions if / else. At the same time, it can also abstract the same business logic out of the function interface, so it can be reused in multiple codes. The specific code is as follows.
summary
Personally, I think it is more suitable to use function in scenarios where there are many judgments on business logic branches, and there are the following advantages
Functional interface instance
The predict < T > interface is a functional interface that accepts an input parameter T and returns a boolean result.
The interface contains a variety of default methods to combine predict into other complex logic (such as and, or, not).
This interface is used to test whether the object is true or false.
We can learn about the use of the functional interface predict < T > through the following example (java8tester. Java):
Execute the above script, and the output result is:
Output all data:
Output all even numbers:
Output all numbers greater than 3:
summary
The above is an example of Java 8 function interface and functional interface introduced by Xiaobian. I hope it will be helpful to you. If you have any questions, please leave me a message and Xiaobian will reply to you in time. Thank you very much for your support for the programming tips website!