函数式接口
- 特点
- 函数式接口即只有一个抽象方法的接口
- @FunctionalInterface注解可以帮助编译器识别定义的接口是否是函数式接口
- 用于函数的定义和使用,可以作为参数传入,可以作为返回值返回
- 常用接口
- Supplier接口
仅包含一个无参的方法: T get() ,用来获取一个泛型参数指定类型的对象数据。函数体内返回数据。
public class demo1 {
public static void print(Supplier<String> s) {
System.out.println(s.get());
}
public static void main(String[] args) {
String msg = "hello";
String msg2 = " son";
print(()->msg+msg2);
}
}
- Consumer
与Supplier接口相反,它不是生产一个数据,而是消费一个数据, 其数据类型由泛型决定。 接收一个数据,在函数体内处理。
import java.util.function.Consumer;
public class demo2 {
public static void upper(String s,Consumer<String> c) {
c.accept(s);
}
public static void main(String[] args) {
String str= "abcde";
upper(str,s->System.out.println(s.toUpperCase()));
}
}
- andThen接口
操作组合,其方法的参数和返回值全都是 Consumer 类型
import java.util.function.Consumer;
public class demo3 {
public static void consumeString(Consumer<String> one, Consumer<String> two){
one.andThen(two).accept("hello!");
}
public static void main(String[] args) {
consumeString(s->System.out.println(s), s->System.out.println(s));
}
}
- Predicate接口
对某种类型的数据进行判断,从而得到一个boolean值结果。
抽象方法:test(T t)
默认方法and,or,negate
import java.util.function.Predicate;
public class demo4 {
public static void testLength(Predicate<String> pre) {
boolean res = pre.test("fasgawrfaha");
System.out.println(res);
}
public static void main(String[] args) {
testLength(s->s.length()>3);
}
}
-
Funciont接口
映射,或者类型转换,根据一个类型的数据得到另一个类型的数据,前者称为前置条件, 后者称为后置条件。- 抽象方法:R apply(T t),给个T类型的t,返回一个R类型
- 默认方法:andThen(),和Consumer类似,多次转换
import java.util.function.Function;
public class demo5 {
public static void trans(Function<String, Integer> func) {
Integer apply = func.apply("123151");
System.out.println(apply);
}
public static void main(String[] args) {
trans(s->Integer.parseInt(s));
}
}
方法引用
lambda表示式简化了接口使用的书写,而方法应用又对某些特殊的lambda表达式进行了书写简化。lambda表达式的函数体部分一般是我们定义的操作,如果只是调用某些已有的函数或类对象的方法,则通过方法应用符号 "::"进行简写。
- 对象名引用成员方法
- 表示式:()->obj.objMethod()
- 方法引用:obj::objMethod
- 类引用静态方法
- 表示式:s->System.out.println(s);
- 方法引用:System.out::println
- super引用
- 表达式:()->super.Method()
- 引用:super::Method
- this引用
- 表达式:()->this.Method()
- 引用:this::Method
- 构造函数的引用
- 表达式:name->new Person(name)
- 引用:Person::new
- 数组的构造器
- 表达式:length->new int[length]
- 引用:int[]::new