Java 8 Built-in functional interface for new features
In the previous blog Lambda expression, referred to the functional interface provided by Java 8. In this article, we'll introduce Java's 84 most basic functional interfaces
For a reference to a method, you need to define an interface in strict terms. No matter how we operate, there are only four interfaces that are actually possible to operate.
Java 8 provides a functional interface package java.util.function.*, under which there are many functional interfaces built into Java 8. But basically it's divided into four basic types:
Functional Interface (function)
Takes T as input, returns R as output, and includes the default method for combining other functions.
@FunctionalInterface public
Interface Function<t, r> {
R apply (t);
}
Sample code
The public static void main (string[] args) {
//is used here for the Java8 method reference, functional-type Interface!
function<string,boolean> Function = "Hello Java":: EndsWith;
System.out.println (function.apply ("Java"));
Consumption type interface (Consumer)
Takes T as input, does not return any content, represents an operation on a single parameter.
@FunctionalInterface Public
interface Consumer<t> {
void accept (t);
}
Sample code
Class testdemo{
//This method has no return value, but has input parameters public
void Fun (String str) {
System.out.println (str)
;
}
public class Testfunctional {public
static void Main (string[] args) {
Testdemo demo = new Testdemo ();
Consumption-type interface, only input parameters, no output parameters
consumer<string> Consumer = Demo:: Fun;
Consumer.accept ("");
}
}
Supply-type interface (Supplier)
No input parameters, only t returns output
@FunctionalInterface Public
interface supplier<t> {
T get ();
}
Sample code
public class Testfunctional {public
static void Main (string[] args) {
//Vendor type interface, only output parameters, no input Parameters!
supplier<string> Supplier = "Java 8":: toUpperCase;
System.out.println (Supplier.get ());
}
Assertion type interface (predicate)
Takes T as input, returns a Boolean value as output, which contains a variety of default methods to synthesize the predicate group into other complex logic (with,,, or non).
@FunctionalInterface Public
interface Predicate<t> {
boolean test (t);
}
Sample code
public class Testfunctional {public
static void Main (string[] args) {
//assertion type interface. There are input parameters, output parameters are Boolean
predicate<string> predicate = "Android":: equalsignorecase;
System.out.println (Predicate.test ("Android"));
}
So in Java 8 because there are more than four functional interfaces, so it is generally very few users to define a new functional interface!
Thank you for reading, I hope to help you, thank you for your support for this site!