Java 函数式编程 - 组成
函数式组成是指将多个函数组合成单个函数的技术。我们可以组合 Lambda 表达式。Java 提供内建支持,使用谓词和函数类。以下举例说明如何使用谓词方法组合两个函数。
import java.util.function.Predicate;
public class FunctionTester {
public static void main(String[] args) {
Predicate<String> hasName = text -> text.contains("name");
Predicate<String> hasPassword = text -> text.contains("password");
Predicate<String> hasBothNameAndPassword = hasName.and(hasPassword);
String queryString = "name=test;password=test";
System.out.println(hasBothNameAndPassword.test(queryString));
}
}
输出
true
谓词提供 and() 和 or() 方法来组合函数。而 函数提供 compose 和 andThen 方法来组合函数。以下举例说明如何使用函数方法组合两个函数。
import java.util.function.Function;
public class FunctionTester {
public static void main(String[] args) {
Function<Integer, Integer> multiply = t -> t *3;
Function<Integer, Integer> add = t -> t + 3;
Function<Integer, Integer> FirstMultiplyThenAdd = multiply.compose(add);
Function<Integer, Integer> FirstAddThenMultiply = multiply.andThen(add);
System.out.println(FirstMultiplyThenAdd.apply(3));
System.out.println(FirstAddThenMultiply.apply(3));
}
}
输出
18 12
广告