1. Conditions for using Lambda expressions
3. Four core functional interfaces
Stage 1: Implement Function interface
1. Conditions for using Lambda expressions
-
The interface must be defined first and the relevant methods can be used only after creating them.
-
This is very inconvenient. In fact, Java 8 already has many built-in interfaces.
-
For example, there are four functional interfaces below, so users rarely define new functional interfaces.
2. Functional interface
The biggest feature of Java8 is functional interfaces . All interfaces marked with @Functionallnterface annotation are functional interfaces.
3. Four core functional interfaces
The four core functional interfaces built into Java8
interface | Entering | return value | abstract method | describe |
Consumer<T> | T | none | void accept(T t); | Consumer interface: with input parameters and no return value |
Supplier<T> | none | T | T get(); | Supply interface: no input parameters, return value |
Function<T,R> | T | R | R apply(T t); | Functional interface: There are input parameters and return values. |
Predicate<T> | T | boolean | boolean test(T t); | Assertive interface: There are input parameters and the return value type is boolean |
4. Function
-
Pass in a value, calculate it through the function, and return another value.
-
T: input parameter type, R: output parameter type
-
Calling method: Rapply(T t)
/**
* @param <T> the type of the input to the function
* @param <R> the type of the result of the function
*
*/
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
}
-
Function: Extract the conversion logic and decouple it
-
Don't think it's too complicated, it's just an interface
4.1 Custom implementation
Stage 1: Implement Function interface
import java.util.function.Function;
public class FunctionObj implements Function {
@Override
public Object apply(Object o) {
return o + "经过apply处理拼接上了";
}
}
Stage 2: Create method
import lombok.extern.slf4j.Slf4j;
import java.util.function.Function;
@Slf4j
public class Main {
public static void test(String input,Function function){
log.info("{}",function.apply(input));
}
}
Stage 3: Call method
import lombok.extern.slf4j.Slf4j;
import java.util.function.Function;
@Slf4j
public class Main {
public static void main(String[] args) {
test("Function 自定义实现:",new FunctionObj());
}
public static void test(String input,Function function){
log.info("{}",function.apply(input));
}
}
Stage 4: Execution results
4.2 General use
Function<Integer, Integer> func = p -> {
log.info("我是函数");
return p * 100;
};
log.info("{}",func.apply(10));
// 简写
Function<Integer, Integer> func1 = p -> p * 100;
log.info("{}",func1.apply(20));