查看源码可以得知此函数标有@FunctionalInterface 是java8新特性函数式接口,其中泛型T是传入的参数类型,泛型R是返回值的类型。
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
Objects.requireNonNull(before);
return (V v) -> apply(before.apply(v));
}
default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t) -> after.apply(apply(t));
}
}
举个栗子,看看怎么使用
1.apply(T t)方法
首先定义function变量,i->i*10是Lambda表达式,当输入参数i时,执行表达式i*10,实际工作中可以是具体的逻辑代码。执行function.apply(5)时,相当于5是参数i,执行5*10,得出Integer类型的50返回结果。返回值的类型是由定义Function函数的泛型决定的
public static void main(String[] args) {
Function<Integer, Integer> function = i -> i*10;
Integer apply = function.apply(5);
System.out.println(apply);//50
Function<Integer, String> function1 = i ->i+1+"元" ;
String apply1 = function1.apply(8);
System.out.println(apply1);//9元
}
2.compose(Function<? super V, ? extends T> before)方法
compose方法的参数是一个Function类型的方法,当我们执行 String apply2 = function1.compose(function).apply(5);时,拿到参数5先执行function的函数表达式,得到50,然后再把结果50当作function1的参数,执行function1表达式,最后返回String类型的结果值。
总结:形如A.compose(B).apply(T),先执行B表达式,再执行A表达式。
public static void main(String[] args) {
Function<Integer, Integer> function = i -> i*10;
Integer apply = function.apply(5);
System.out.println(apply);//50
Function<Integer, String> function1 = i ->i+1+"元" ;
String apply1 = function1.apply(8);
System.out.println(apply1);//9元
String apply2 = function1.compose(function).apply(5);
System.out.println(apply2);//51元
}
3.andThen(Function<? super R, ? extends V> after) 方法
andThen方法则是和compose相反。
总结:A.andThen(B).apply(T),先执行A表达式,再执行B表达式。
如果觉得有收获,请为互联网美少女刘可爱点个赞吧。
public static void main(String[] args) {
Function<Integer, Integer> function = i -> i*10;
Integer apply = function.apply(5);
System.out.println(apply);//50
Function<Integer, String> function1 = i ->i+1+"元" ;
String apply1 = function1.apply(8);
System.out.println(apply1);//9元
//注意这里和上个的顺序不一样
String apply2 = function.andThen(function1).apply(5);
System.out.println(apply2);//51元
}