java8中函数式接口特性

文章介绍了Java中的函数式接口,如Function用于有参有返回型操作,Consumer表示消费型函数,Supplier提供数据而不接受参数,Runnable则为无参无返回型。通过示例展示了如何使用apply方法以及compose和andThen方法来组合函数操作。
摘要由CSDN通过智能技术生成

使用注解 @FunctionalInterface 标识,并且只包含一个 抽象方法 的接口是 函数式接口

1.Function 有参有返回型函数、Function 函数的表现形式为接收一个参数,并返回一个值

2.Consumer 消费型函数、Consumer函数的表现形式为接收一个参数,没有返回值

3.Supplier 供给型函数、表现形式为 不接受参数、只返回数据

4.Runnable 无参无返回型函数、表现形式为无参无返回型函数

例子一:

   /**
     * 将该函数应用到给定的参数
     * @param t 函数的参数
     * @return 函数的结果
     */
    R apply(T t);
public static int testFunction(int i, Function<Integer,Integer> function) {
    return function.apply(i);
}
 
System.out.println(testFunction(2,i -> i * 2 + 1));

输出结果是 5

在生产上应用:
在这里插入图片描述
在这里插入图片描述
例子二:

  /**
    * 返回一个组合函数, 首先执行before function的apply方法, 将它的返回作为输入参数再应用当前的function
    */
    default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
        Objects.requireNonNull(before);
        return (V v) -> apply(before.apply(v));
    }
public static int testCompose(int a, Function<Integer, Integer> funA, 
   Function<Integer, Integer> funB) {
      return funA.compose(funB).apply(a);
}
 
System.out.println("compose"+testCompose(5, value -> value - 1,value -> value * 2));

结果:先执行value -> value * 2 >>5*2=10,再执行value -> value - 1, 10-1=9

例子三:

   /**
    * 返回一个组合函数, 它是先调用当前函数的apply方法, 再将其结果作为输入参数传递给after function调用apply()
    */
    default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
        Objects.requireNonNull(after);
        return (T t) -> after.apply(apply(t));
    }
public static int andThen(int a, Function<Integer, Integer> funA, 
    Function<Integer, Integer> funB) {
         return funA.andThen(funB).apply(a);
 
System.out.println("andThen 结果:"+andThen(5, value -> value - 1,value -> value * 2));

先执行value -> value - 1 >>5-1=4,在执行value -> value * 2 结果是8
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值