理解Java函数式编程Function

218 阅读1分钟

个人惯例先贴demo代码,同Predicate那篇一样本文还是帮助理解Function中的函数

public interface MyFunction<R,T> {
    public R process(Function<R, T> function,T t);
}
 
public class TestMyFunction implements MyFunction<String, String>{
 
    @Override
    public String process(Function<String, String> function, String o) {
        return function.andThen(function).apply(o);
    }

    public static void main(String[] args) {
        TestMyFunction testMyFunction = new TestMyFunction();
        String str = "lambda";
        String result = testMyFunction.process((String s) -> {
            return "hello " +s;
        }, str);
        System.out.println(result);
    }
}

我们挑一个andThen函数

default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
    Objects.requireNonNull(after);
    return (T t) -> after.apply(apply(t));
}

after.apply(apply(t))是一个 Function 实现类的apply方法实现,是一个整体 该函数会先调用 apply(t),即会先调用

image.png 这个Functionapply方法,而这个方法即这部分

image.png andThen里的Function 其实我又把上一个Function重新传进去了了,实际业务中可以重新定义一个Function。 而这个apply方法

image.png 其实就是对这个Function实现apply方法整体调用

image.png