函数式接口

首页

函数式接口

一个接口中,只有一个方法,可以定义为函数式接口

主要作用

调用函数式接口可以让代码更加优雅。举例说明,如果要计算两个数的值,并使用计算后的结果。传统方式是写一个方法,进行调用。现在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还定义了很多

接口说明
BiFunctionR apply(T t, U u);接受两个参数,返回一个值,代表一个二元函数;
DoubleFunctionR apply(double value);只处理double类型的一元函数;
IntFunctionR apply(int value);只处理int参数的一元函数;
LongFunctionR apply(long value);只处理long参数的一元函数;
ToDoubleFunctiondouble applyAsDouble(T value);返回double的一元函数;
ToDoubleBiFunctiondouble applyAsDouble(T t, U u);返回double的二元函数;
ToIntFunctionint applyAsInt(T value);返回int的一元函数;
ToIntBiFunctionint applyAsInt(T t, U u);返回int的二元函数;
ToLongFunctionlong applyAsLong(T value);返回long的一元函数;
ToLongBiFunctionlong applyAsLong(T t, U u);返回long的二元函数;
DoubleToIntFunctionint applyAsInt(double value);接受double返回int的一元函数;
DoubleToLongFunctionlong applyAsLong(double value);接受double返回long的一元函数;
IntToDoubleFunctiondouble applyAsDouble(int value);接受int返回double的一元函数;
IntToLongFunctionlong applyAsLong(int value);接受int返回long的一元函数;
LongToDoubleFunctiondouble applyAsDouble(long value);接受long返回double的一元函数;
LongToIntFunctionint applyAsInt(long value);接受long返回int的一元函数;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值