Java 函数式编程 - 组合
功能组合是指将多个功能组合在一起形成单个功能的技术。我们可以将 lambda 表达式组合在一起。Java 使用 Predicate 和 Function 类提供内置支持。以下示例展示了如何使用谓词方法组合两个函数。
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
Predicate提供 and() 和 or() 方法来组合函数。而Function提供了 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