如果您需要TriFunction,请执行以下操作:
@FunctionalInterface
interface TriFunction<A,B,C,R> {
R apply(A a, B b, C c);
default <V> TriFunction<A, B, C, V> andThen(
Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (A a, B b, C c) -> after.apply(apply(a, b, c));
}
}
以下小程序显示了如何使用它。请记住,结果类型被指定为最后一个泛型类型参数。
public class Main {
public static void main(String[] args) {
BiFunction<Integer, Long, String> bi = (x,y) -> ""+x+","+y;
TriFunction<Boolean, Integer, Long, String> tri = (x,y,z) -> ""+x+","+y+","+z;
System.out.println(bi.apply(1, 2L)); //1,2
System.out.println(tri.apply(false, 1, 2L)); //false,1,2
tri = tri.andThen(s -> "["+s+"]");
System.out.println(tri.apply(true,2,3L)); //[true,2,3]
}
}
我猜想TriFunction是否有实际用途,java.util.*
或者java.lang.*
已经定义好了。我永远不会超出22个参数;-)我的意思是,所有允许流收集的新代码都不需要TriFunction作为任何方法参数。因此不包括在内。
更新
为了完整起见,并在另一个答案(与currying相关)中遵循破坏性函数的解释,以下是在没有附加接口的情况下如何模拟TriFunction的方法:
Function<Integer, Function<Integer, UnaryOperator<Integer>>> tri1 = a -> b -> c -> a + b + c;
System.out.println(tri1.apply(1).apply(2).apply(3)); //prints 6
当然,可以通过其他方式组合功能,例如:
BiFunction<Integer, Integer, UnaryOperator<Integer>> tri2 = (a, b) -> c -> a + b + c;
System.out.println(tri2.apply(1, 2).apply(3)); //prints 6
//partial function can be, of course, extracted this way
UnaryOperator partial = tri2.apply(1,2); //this is partial, eq to c -> 1 + 2 + c;
System.out.println(partial.apply(4)); //prints 7
System.out.println(partial.apply(5)); //prints 8
尽管对支持lambda之外的功能编程的任何语言来说,使用currying都是很自然的,但是Java不是以这种方式构建的,尽管可以实现,但是代码却难以维护,有时甚至难以阅读。但是,它作为练习非常有帮助,有时部分函数在您的代码中应有的地位。