Java8的Function函数式接口

源码
@FunctionalInterface
public interface Function<T, R> {
    R apply(T t);
 
    default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
        Objects.requireNonNull(before);
        return (V v) -> apply(before.apply(v));
    }
 
    default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
        Objects.requireNonNull(after);
        return (T t) -> after.apply(apply(t));
    }
 
    static <T> Function<T, T> identity() {
        return t -> t;
    }
}
  • apply( )
    就是lambda中需要自己实现的抽象方法

    栗子:
        Function<Integer, Integer> function1 = x -> x * 2;
        System.out.println(function1.apply(10));

输出的结果是 20
为了突出T和R,另一个栗子

        Function<Integer, String> function3 = x -> x * 2 + " string ";
        System.out.println(function3.apply(10));

输出的结果是 20 string

  • compose()
    是把两个function组合起来,首先执行compose中的function
        Function<Integer, Integer> function1 = x -> x * 2;
        System.out.println(function1.apply(10));
        Function<Integer, String> function3 = x -> x * 2 + " string ";
        System.out.println(function3.apply(10));
        //这里把function1和function3 合起来了
        System.out.println(function3.compose(function1).apply(10));

输出结果是
20
20 string
40 string

很明显,首先执行了compose里面的function1,然后再执行的function3。

  • andThen()
    是把两个function组合起来,后执行andThen中的function

    这个就不写示例了,正好是与compose()方法相反的。

  • identity()
    返回一个方法,把参数原样输出

        Function<Integer,Integer> function4=Function.identity();
        System.out.println(function4.apply(10));

输出 10
说实话不知道这有啥用。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值