In Guava, we can do stuff like
Predicate<String> isEmpty = Predicates.compose(String::length, Integer.valueOf(0)::equals); // contrived, I know
Can we do something similar in Java 8? For example
Predicate<Integer> isZero = Integer.valueOf(0)::equals;
Predicate<String> isEmpty = isZero.compose(String::length);
or a library function that achives the same?
Note that I'm not asking about how to do this myself (s -> isZero.test(s.length)
works fine) or why this doesn't work in line (Lambda types are inferred and all that)
You can easily write a compose
method and use that in multiple places:
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));
}
}
(I removed references to Integer.ZERO
as that doesn't exist...)
See more on this question at Stackoverflow