A functional interface is an interface that has only one abstract method and is used as an assignment destination for lambda expressions and method references. I tried to summarize the standard functional interface
As a standard functional interface, typical method types are defined in the java.util.function package.
| interface | Method | Description |
|---|---|---|
| Function <T, R> | R apply (T t) | Takes a T-type argument and returns an R-type result |
| Consumer <T> | void accept (T t) | Receives T-type arguments and returns no results |
| Predicate <T> | boolean test(T t) | Takes a T-type argument and returns the result of a boolean value |
| Supplier <T> | T get() | Returns a T-type result with no arguments |
Sample.java
// Function<T, R>
//Example: Returns the string length of the argument
Function<String, Integer> function = String::length;
System.out.println(function.apply("12345")); // 5
// Consumer<T>
//Example: Output the argument string length
Consumer<String> consumer = str -> System.out.println(str.length());
consumer.accept("12345"); // 5
// Predicate<T>
//Example: In the argument string"foo"Judgment whether is included
Predicate<String> predicate = str -> Objects.nonNull(str) && str.contains("foo");
System.out.println(predicate.test("foo bar")); // true
// Supplier<T>
//Example:"Sample"return it
Supplier<String> supplier = () -> "Sample";
System.out.println(supplier.get()); // Sample
You can combine standard functional interfaces to create new functional interfaces
Synthesize using compose, ʻandThen (The difference between compose and ʻandThen is the order of composition)
Predicate system can be synthesized using ʻand, ʻor, negate
Sample.java
//Function composition of Function
Function<String, Integer> function1 = String::length;
Function<Integer, Integer> function2 = i -> i * 100;
//When using compose
Function<String, Integer> newFunction1 = function2.compose(function1);
//When using andThen
Function<String, Integer> newFunction2 = function1.andThen(function2);
System.out.println(newFunction1.apply("12345")); // 500
System.out.println(newFunction2.apply("12345")); // 500
//Predicate function composition
Predicate<Integer> predicate1 = i -> i % 2 == 0; //Judging whether it is an even number
Predicate<Integer> predicate2 = i -> i >= 100; //Judgment whether it is 100 or more
//Determine if it is even and 100 or more
Predicate<Integer> newPredicate1 = predicate1.and(predicate2);
//Determine if it is odd and less than 100(negate()Is a logical negation)
Predicate<Integer> newPredicate2 = predicate1.negate().and(predicate2.negate());
System.out.println(newPredicate1.test(100)); // true
System.out.println(newPredicate2.test(99)); // true
Recommended Posts