Java 8 new features-5 built-in functional interfaces, new features-5
In the previous blog Lambda expressions, I mentioned functional interfaces provided by Java 8. In this article, we will introduce the four most basic functional interfaces of Java 8.
For method reference, an interface must be defined strictly. No matter how we operate, there are actually only four possible interfaces.
Java 8 provides a functional interface packageJava. util. function .*In this package, there are many Java 8 built-in functional interfaces. However, there are basically four basic types:
- Function)
- T is used as the input, and R is returned as the output. It also contains the default method used in combination with other functions.
@FunctionalInterfacepublic interface Function<T, R> { R apply(T t);}
- Sample Code
Public static void main (String [] args) {// the Java 8 method reference is used here, a functional interface! Function <String, Boolean> function = "Hello Java": endsWith; System. out. println (function. apply ("Java "));}
- Consumer interface (Consumer)
- T is used as the input, and no content is returned, indicating the operation on a single parameter.
@FunctionalInterfacepublic interface Consumer<T> { void accept(T t);}
- Sample Code
Class TestDemo {// This method does not return a value, but there is an input parameter public void fun (String str) {System. out. println (str) ;}} public class TestFunctional {public static void main (String [] args) {TestDemo demo = new TestDemo (); // consumption interface, only input parameters, no output parameter Consumer <String> consumer = demo: fun; consumer. accept ("");}}
- Supply interface (Supplier)
- No input parameter, only T returns the output
@FunctionalInterfacepublic interface Supplier<T> { T get();}
- Sample Code
Public class TestFunctional {public static void main (String [] args) {// supplier type interface, only output parameters, no input parameters! Supplier <String> supplier = "java 8": toUpperCase; System. out. println (supplier. get ());}}
- Predicate)
- T is used as the input, and a Boolean value is returned as the output. This interface contains multiple default methods to combine Predicate into other complex logic (and, or, not ).
@FunctionalInterfacepublic interface Predicate<T> { boolean test(T t);}
- Sample Code
Public class TestFunctional {public static void main (String [] args) {// asserted type interface. There are input parameters. The output parameters are boolean values: Predicate <String> predicate = "Android": inclusignorecase; System. out. println (predicate. test ("android "));}}
Therefore, because of the above four functional interfaces in Java 8, users rarely define new functional interfaces!