New features of Java 8 built-in functional interface
In a previous blog post, Lambda expression, we mentioned the functional interface provided by Java 8. In this article, we will introduce the four most basic functional interfaces in Java 8.
For references to methods, strictly speaking, an interface needs to be defined. No matter how we operate, there are actually only four interfaces that are possible to operate.
Java 8 provides the functional interface package java.util.function.*, under which there are many functional interfaces built into Java 8. However, it is basically divided into four basic types:
Functional interface (Function)
Taking T as input and R as output, it also contains the default method combined with other functions.
@FunctionalInterfacepublic interface Function<T, R> { R apply(T t);} Sample code
public static void main(String[] args) { // Here we use Java8 method reference, functional functional interface! Function<String,Boolean> function = "Hello Java" :: endsWith; System.out.println(function.apply("Java"));} Consumer interface
Take T as input without returning anything, indicating an operation on a single parameter.
@FunctionalInterfacepublic interface Consumer<T> { void accept(T t);} Sample code
class TestDemo{ //This method has no return value, but there are input parameters public void fun(String str){ System.out.println(str); }}public class TestFunctional { public static void main(String[] args) { TestDemo demo = new TestDemo(); //Consumer type interface, only input parameters, no output parameters Consumer<String> consumer = demo :: fun; consumer.accept(""); }}
Supplier
No input parameters, 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()); }} Assertional interface (Predicate)
Taking T as input and returning a Boolean as output, the interface contains a number of default methods to combine Predicate into other complex logic (AND, OR, non).
@FunctionalInterfacepublic interface Predicate<T> { boolean test(T t);} Sample code
public class TestFunctional { public static void main(String[] args) { //Assert type interface. There are input parameters, the output parameters are boolean Predicate<String> predicate = "Android" :: equalsIgnoreCase; System.out.println(predicate.test("android")); }}Therefore, in Java 8, since there are the above four functional interfaces, it is generally rare for users to define new functional interfaces!
Thank you for reading, I hope it can help you. Thank you for your support for this site!