Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 650
Chriss Avatar asked Feb 29 '16 13:02

Chriss


1 Answers

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();
like image 55
wero Avatar answered Nov 16 '22 06:11

wero