简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM