Chriss
Chriss

Reputation: 5639

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?

Upvotes: 7

Views: 2975

Answers (1)

wero
wero

Reputation: 32980

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();

Upvotes: 16

Related Questions