How to use guava predictions as a filter in the Java 8 stream API
•
Java
Guava predictions cannot be used as a filter for the Java 8 streaming API
For example, this is not possible:
Number first = numbers.stream()
.filter( com.google.common.base.Predicates.instanceOf(Double.class)))
.findFirst()
.get();
How is it possible to convert a guava predicate to a Java 8 predicate, as follows:
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 predictions in Java 8?
Solution
The method handle of the apply method of the guava predicate is a functional interface that can be used as a filter:
Number first = numbers.stream()
.filter(Predicates.instanceOf(Double.class)::apply)
.findFirst()
.get();
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
