Lambda函数式接口
匿名函数式接口用法
- 只要是函数式接口就可以用Lambda表达式简化。
- 接口中有且只有一个未实现的方法就叫函数式接口。
- 可以在接口上添加检查注解@FunctionalInterface 查看是否符合函数式接口规范。
- Lambda表达式是在程序运行的时候动态生成class。
完整写法
参数列表(参数类型 参数名) + 箭头 -> + 方法体 {代码块}
public class Test {
@FunctionalInterface
interface LambdaInterface{
int way(int i,int j);
}
public static void main(String[] args) {
LambdaInterface lambdaInterface = (int i,int j) -> {
return i+j;
};
int sum = lambdaInterface.way(2, 2);
LambdaInterface lambdaInterface1 = (int i,int j) -> {
return i-j;
};
int sub = lambdaInterface1.way(2, 1);
System.out.println("两数相加值为:" + sum);
System.out.println("两数相减值为:" + sub);
}
}
简化写法
- 参数类型可以不写,只写参数名。参数列表最少只有一个()或者只有一个参数名。
- 方法体只有一句话的情况下,{}可以省略
public class Test {
@FunctionalInterface
interface LambdaInterface{
int way(int i);
}
public static void main(String[] args) {
LambdaInterface lambdaInterface = i -> i+1;
int way = lambdaInterface.way(2);
System.out.println("当前值默认加一:" + way);
}
}
Function函数式接口
java.util.function包下的所有function定义
Supplier
提供型接口: 没有参数,只有返回值
调用的函数方法:get
public class Test {
public static void main(String[] args) {
Supplier<String> supplier = () -> "岳阳楼下喝可乐";
System.out.println("输入值为:" + supplier.get());
}
}
Predicate
断言型接口:有一个输入参数,返回值只能是布尔值
调用的函数方法:test
public class Test {
public static void main(String[] args) {
Predicate<String> isNull = str -> str.isBlank() ;
System.out.println("输入是否为空" + isNull.test(""));
}
}
Function
函数型接口, 有一个输入参数 T ,有一个输出 R
调用的函数方法:apply
public class Test {
public static void main(String[] args) {
Function<String,Integer> function = Integer::parseInt;
System.out.println("字符串类型转数值类型:" + function.apply("123"));
}
}
Consumer
消费型接口: 只有输入,没有返回值
调用的函数方法:accept
public class Test {
public static void main(String[] args) {
Consumer<Integer> consumer = num ->{
if (num % 2 == 0){
System.out.println("当前值"+num+"为偶数");
}else {
System.out.println("当前值"+num+"为奇数");
}
};
consumer.accept(13);
}
}