介绍一下Java的BiFunction

java的函数式接口是java8引入的很重要的特性,也让日常代码有了比较大的风格转变
这里介绍下BiFunction,
BiFunction的代码很短

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
@FunctionalInterface
public interface BiFunction<T, U, R> {

/**
* Applies this function to the given arguments.
*
* @param t the first function argument
* @param u the second function argument
* @return the function result
*/
R apply(T t, U u);

/**
* Returns a composed function that first applies this function to
* its input, and then applies the {@code after} function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param <V> the type of output of the {@code after} function, and of the
* composed function
* @param after the function to apply after this function is applied
* @return a composed function that first applies this function and then
* applies the {@code after} function
* @throws NullPointerException if after is null
*/
default <V> BiFunction<T, U, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t, U u) -> after.apply(apply(t, u));
}
}

默认的方法就跟普通的FunctionalInterface一样,就有一个apply方法,只是这里的特殊点有两个

返回值作为参数

这个BiFunction有三个泛型参数,T,U跟R,而这个R其实是具体方法的返回值
比如我们简单实现一个字符串拼接

1
2
BiFunction<String, String, String> biDemo = (s1, s2) -> s1 + s2;
System.out.println(biDemo.apply("hello ", "world"));

apply返回的就是参数R

andThen

这个方法是可以让结果再调用传入的方法,并返回结果

1
2
Function<String, Integer> funcDemo = String::length;
System.out.println(biDemo.andThen(funcDemo).apply("hello ", "world"));

定义了个函数接口,并且给了实现,就是字符串获取长度
然后传给biDemo,这样就可以输出拼接后的字符串长度

组合使用

1
2
3
public <T1, T2, R1, R2> R2 combination(T1 t1, T2 t2, BiFunction<T1, T2, R1> biFunction, Function<R1, R2> function) {
return biFunction.andThen(function).apply(t1, t2);
}

这样就把前面的两个方法串起来了