函数式接口
一个接口中,只有一个方法,可以定义为函数式接口
主要作用
调用函数式接口可以让代码更加优雅。举例说明,如果要计算两个数的值,并使用计算后的结果。传统方式是写一个方法,进行调用。现在jdk中有函数式接口,可以直接用。就不用写了。
Function<T , R>
接口中的T是参数类型,R是返回值类型,使用apply方法传参,
函数式接口定义好后,使用该函数式接口就是使用返回值。
Function<Integer,String> fun = i -> i+" * 2 = "+i*2;
System.out.println(fun.apply(2));
Predicate
接口中的T为参数,返回值类型固定为boolean,使用test方法传参
Predicate<String> pre = (s) -> s.equals("poin");
System.out.println(pre.test("poin"));
Consumer
接口中的T为参数,返回值为空,使用accept方法传参
Consumer<String> con = (s) -> System.out.println(s);
con.accept("天天");
Supplier
接口中的T为返回值类型,使用get方法获取返回值
Supplier<String> sup = () -> {
return new Random().nextInt(100) + "";
};
System.out.println(sup.get());
上面的函数都是一元函数
上面函数都是一元函数,传参都是单个传参,如果要传2个参数,则可以使用二元函数
BiFunction<T,U,R>
R是返回值类型,T和U是入参类型,比如要写一个加法
BiFunction<Integer, Integer, Integer> add = (x, y) -> x + y;
System.out.println(add.apply(10, 10));
有了一元和二元,比如想要一个三元,计算三个数的累加,就可以进行组合
@FunctionalInterface
public interface TernaryFunction<T,U,V,R> {
R apply(T t, U u, V v);
default public BiFunction<T, U, R> get(V v) {
return (t, u) -> this.apply(t, u, v);
}
}
public class F1 {
public static void main(String[] args) {
TernaryFunction<Integer, Integer, Integer, Integer> add3 = (x, y, z) -> x + y + z;
System.out.println(add3.apply(1, 2, 3));
}
}
上面定义的三元函数中,用到了函数的柯里化技术(目前还没有搞懂)
Function接口中,jdk还定义了很多
接口 | 说明 |
---|---|
BiFunction | R apply(T t, U u);接受两个参数,返回一个值,代表一个二元函数; |
DoubleFunction | R apply(double value);只处理double类型的一元函数; |
IntFunction | R apply(int value);只处理int参数的一元函数; |
LongFunction | R apply(long value);只处理long参数的一元函数; |
ToDoubleFunction | double applyAsDouble(T value);返回double的一元函数; |
ToDoubleBiFunction | double applyAsDouble(T t, U u);返回double的二元函数; |
ToIntFunction | int applyAsInt(T value);返回int的一元函数; |
ToIntBiFunction | int applyAsInt(T t, U u);返回int的二元函数; |
ToLongFunction | long applyAsLong(T value);返回long的一元函数; |
ToLongBiFunction | long applyAsLong(T t, U u);返回long的二元函数; |
DoubleToIntFunction | int applyAsInt(double value);接受double返回int的一元函数; |
DoubleToLongFunction | long applyAsLong(double value);接受double返回long的一元函数; |
IntToDoubleFunction | double applyAsDouble(int value);接受int返回double的一元函数; |
IntToLongFunction | long applyAsLong(int value);接受int返回long的一元函数; |
LongToDoubleFunction | double applyAsDouble(long value);接受long返回double的一元函数; |
LongToIntFunction | int applyAsInt(long value);接受long返回int的一元函数; |