Ris*_*ain 0 java lambda functional-programming java-8
Java-8带有Function和BiFunction。我们如何链接多个Function或Bifunction实例。这样一个人的输出成为另一个人的输入Function。我创建了简单的函数和双功能来说明。
import java.util.function.BiFunction;
import java.util.function.Function;
class FunctionSample1 {
public static void main(String[] args) {
BiFunction<Integer, Integer, Integer> mul = (x, y) -> {
return x * y;
};
BiFunction<Integer, Integer, Integer> div = (x, y) -> {
return x / y;
};
BiFunction<Integer, Integer, Integer> sum = (x, y) -> {
return x + y;
};
BiFunction<Integer, Integer, Integer> sub = (x, y) -> {
return x - y;
};
Function<Integer, Integer> mulfunc = (y) -> {
return y * 9;
};
Function<Integer, Integer> divfunc = (y) -> {
return y / 2;
};
Function<Integer, Integer> sumfunc = (y) -> {
return y + 89;
};
Function<Integer, Integer> subdunc = (y) -> {
return y - 2;
};
}
}
Run Code Online (Sandbox Code Playgroud)
如何将它们链接在一起,无论是使用compose还是andThen获取结果?
双方Function并BiFunction有一个方法andThen(Function)可以帮助您建立由功能。
BiFunction.andThen(Function) = BiFunction
Function.andThen(Function) = Function
Run Code Online (Sandbox Code Playgroud)
例如,
BiFunction<Integer, Integer, Integer> mul = (x, y) -> x * y;
Function<Integer, Integer> times2 = x -> x * 2;
Function<Integer, Integer> minus1 = x -> x - 1;
// r = ((3 * 3) * 2) - 1
Integer r = mul.andThen(times2).andThen(minus1).apply(3, 3);
Run Code Online (Sandbox Code Playgroud)
Function也有方法compose(Function)。
Function1.compose(Function0) = Function0.andThen(Function1) = Function
Run Code Online (Sandbox Code Playgroud)
例如,
// r2 = (3 - 1) * 2
Integer r2 = times2.compose(minus1).apply(3);
Run Code Online (Sandbox Code Playgroud)