Guava Predicates can't be used out of the box as filter with the java 8 streaming API.
E.g this is not possible:
Number first = numbers.stream()
.filter( com.google.common.base.Predicates.instanceOf(Double.class)))
.findFirst()
.get();
How ever it is possible when the guava predicate is converted to a java 8 predicate,like this:
public static <T> Predicate<T> toJava8(com.google.common.base.Predicate<T> guavaPredicate) {
return (e -> guavaPredicate.apply(e));
}
Number first = numbers.stream()
.filter( toJava8( instanceOf(Double.class)))
.findFirst()
.get();
QUESTION: Is there a more elegant way to reuse guava Predicates in java 8?
The method handle for the apply
method of the Guava predicate is a functional interface which can be used as filter:
Number first = numbers.stream()
.filter(Predicates.instanceOf(Double.class)::apply)
.findFirst()
.get();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With