How to use guava Predicates as a filter in java 8 stream api

Guava Predicates cannot be used out of the box as a filter using 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(); 

As soon as possible when the guava predicate is converted to a java 8 predicate, for example:

 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?

+5
source share
1 answer

The method handle for 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(); 
+14
source

Source: https://habr.com/ru/post/1244116/


All Articles