记录项目中function的使用
public static void main(String[] args) {
//apply方式一
Function<String, String> f1 = new Function() {
@Override
public Object apply(Object o) {
return o.toString() + " --f1--";
}
};
System.out.println(f1.apply("hello"));
//hello---f1--
//apply方式二
Function<String, String> f2 = a -> a + "---f2--";
System.out.println(f2.apply("hello"));
//hello --f2--
//compose使用
System.out.println(f1.compose(f2).apply("hello"));
//hello --f1-----f2--
Function<String, String> f3 = a -> a + "---f3--";
System.out.println("test1:" + f1.compose(f2).compose(f3).apply("hello"));
//test1:hello---f3-----f2-- --f1--
System.out.println("test1:" + f1.andThen(f2).andThen(f3).apply("hello"));
//test1:hello --f1-----f2-----f3--
}
}
1,function使用了@FunctionalInterface注解,
是jdk8的新特性:函数式接口。
支持lambda表达式。
@FunctionalInterface
public interface Function<T, R> {
2,R apply(T t)
function提供实现方式,通过apply传递参数(可以传多个),实现function接口方法。
Function<String,String>第一个是参数类型,第二个是返回类型。
3,compose(Function<? super V, ? extends T> before)
参数为function
f1.compose(Function f2)时,先运行f2的逻辑再去运行f1接下来的逻辑,如下:
System.out.println(f1.compose(f2).apply("hello"));
System.out.println(f1.apply(f2.apply("hello")));
//hello---f2-- --f1--
这两段代码是没有区别的,都是通过apply的传参,先去运行f2的逻辑再去运行f1的逻辑。
因为是支持lambda支持,所以可以有下面这种操作
f.compose(f1).compose(f2).compose(f3).apply("hello")
依次的执行顺序是f3,f2,f1,f
4,除了apply和compose方法,还有andThen方法
andThen方法和compose相反,执行顺序是反过来的
System.out.println("test1:" + f1.compose(f2).compose(f3).apply("hello"));
System.out.println("test1:" + f1.andThen(f2).andThen(f3).apply("hello"));
//test1:hello---f3-----f2-- --f1--
//test1:hello --f1-----f2-----f3--