JDK8新特性 -- Function接口: apply,andThen,compose

1 Function<T, R>中的T, R表示接口输入、输出的数据类型。

  • R apply(T t)

  • apply
  • .例子:func是定义好的Function接口类型的变量,他的输入、输出都是Integer类型,调用calculate方法时,将func作为参数传入,对参数5进行处理。

    FunctionTest functionTest = new FunctionTest();
    // return e + 5;就是apply方法的具体实现
    Function<Integer, String> func = e -> {return String.valueOf(e + 6);};
    String result = functionTest.calculate(5, func);
    System.out.println(result);

    public String calculate(Integer a, Function<Integer, String> function) {
    return function.apply(a);
    }

  • andThen:

    • 先处理参数,再对返回值使用操作after进行处理。
      Function<Integer, Integer> func = e -> {return e + 5;};
      Function<Integer, Integer> func2 = e -> {return e * 5;};
      //func2即after
      func.andThen(func2).apply(5); // 50

    compose:

    • andThen刚好相反:先使用操作before处理参数,再对返回值进行处理。
      Function<Integer, Integer> func = e -> {return e + 5;};
      Function<Integer, Integer> func2 = e -> {return e * 5;};
      //func2即before
      func.compose(func2).apply(5); // 30
    • compose源码:
      default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
      Objects.requireNonNull(before);
      return (V v) -> apply(before.apply(v));//第一个apply是调用当前接口的方法
      }
    • 注意compose方法的返回值依然是Function<T, R>类型,所以不是
      return this.apply(before.apply(v));

    案例:

  •  public class FunctionTest2 { public static void main(String[] args) { FunctionTest2 functionTest2 = new FunctionTest2(); int result1 = functionTest2.compute(5, e -> e * 5, e -> e + 5); int result2 = functionTest2.compute2(5, e -> e * 5, e -> e + 5); int result3 = functionTest2.compute3(5, e -> e * 5, e -> e + 5); int result4 = functionTest2.compute4(5, e -> e * 5, e -> e + 5); System.out.println(result1);//50 System.out.println(result2);//30 System.out.println(result3);//130 System.out.println(result4);//250 }

    public int compute(int source, Function<Integer, Integer> function1, Function<Integer, Integer> function2) {
    return function1.compose(function2).apply(source);
    }
    public int compute2(int source, Function<Integer, Integer> function1, Function<Integer, Integer> function2) {
    return function1.andThen(function2).apply(source);
    }
    public int compute3(int source, Function<Integer, Integer> function1, Function<Integer, Integer> function2) {
    return function1.andThen(function2).compose(function1).apply(source); //从后往前 25 125 130
    }
    public int compute4(int source, Function<Integer, Integer> function1, Function<Integer, Integer> function2) {
    return function1.compose(function2).andThen(function1).apply(source); } //10*5 50*5
    }

点赞