一、Lambda 表达式 使用条件
-
必须先定义接口,创建相关方法之后才可使用
-
这样做十分不便,其实 java 8 已经内置了许多接口
-
例如下面四个功能型接口,所以用户很少去定义新的函数式接口
二、函数式接口
Java8的最大特性就是函数式接口,所有标注了@Functionallnterface注解的接口都是函数式接口
三、四大核心函数式接口
Java8 内置的四大核心函数式接口
接口 | 入参 | 返回值 | 抽象方法 | 描述 |
Consumer<T> | T | 无 | void accept(T t); | 消费型接口: 有入参,无返回值 |
Supplier<T> | 无 | T | T get(); | 供给型接口: 无入参,有返回值 |
Function<T,R> | T | R | R apply(T t); | 函数型接口:有入参,有返回值 |
Predicate<T> | T | boolean | boolean test(T t); | 断言型接口: 有入参,返回值类型是boolean |
四、Function
-
传入一个值,经过函数的计算,返回另一个值
-
T: 入参类型,R:出参类型
-
调用方法: 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);
}
-
作用: 将转换逻辑提取出来,解耦合
-
不要看过于复杂,就是一个接口
4.1 自定义实现
Stage 1: 实现 Function接口
import java.util.function.Function;
public class FunctionObj implements Function {
@Override
public Object apply(Object o) {
return o + "经过apply处理拼接上了";
}
}
Stage 2: 创建方法
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: 调用方法
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: 执行结果
4.2 常规使用
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));