Java 8中的组合谓词

时间:2016-12-06 09:38:59

标签: java lambda java-8

在番石榴,我们可以做像

这样的事情
Predicate<String> isEmpty = Predicates.compose(String::length, Integer.valueOf(0)::equals); // contrived, I know

我们可以在Java 8中做类似的事情吗?例如

Predicate<Integer> isZero = Integer.valueOf(0)::equals;
Predicate<String> isEmpty = isZero.compose(String::length);

或具有相同功能的库函数?

请注意,我自己并没有询问如何执行此操作(s -> isZero.test(s.length)正常工作)或为什么这不能正常工作(推断Lambda类型和所有这些)

1 个答案:

答案 0 :(得分:3)

您可以轻松编写import java.util.function.*; public class Test { public static void main(String[] args) { Integer zero = 0; Predicate<Integer> isZero = zero::equals; Predicate<String> isEmpty = compose(String::length, isZero); System.out.println(isEmpty.test("")); // true System.out.println(isEmpty.test("x")); // false } // Composition of a function with a predicate public static <T, S> Predicate<T> compose(Function<T, S> first, Predicate<S> second) { return input -> second.test(first.apply(input)); } } 方法并在多个位置使用该方法:

Integer.ZERO

(我删除了对malloc的引用,因为它不存在...)

相关问题