java8中函数式接口特性

使用注解 @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
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_38747892/article/details/131724133
今日推荐