简体   繁体   English

如何在java 8 stream api中使用guava Predicates作为过滤器

[英]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. Guava Predicates不能作为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: 当guava谓词转换为java 8谓词时,如何可能,如下所示:

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? 问题:有没有更优雅的方法在java 8中重用guava Predicates?

The method handle for the apply method of the Guava predicate is a functional interface which can be used as filter: Guava谓词的apply方法的方法句柄是一个可用作过滤器的功能接口:

Number first = numbers.stream()
    .filter(Predicates.instanceOf(Double.class)::apply)
    .findFirst()
    .get();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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