java - Google 馆藏供应商和查找

标签 java guava

我正在寻找一种 Google 集合方法,该方法返回不返回 null 的供应商序列的第一个结果。

我正在考虑使用 Iterables.find() 但在我的 Predicate 中我必须调用我的供应商将结果与 null 进行比较,然后一旦 find 方法返回供应商就必须再次调用它。

最佳答案

考虑到您对 Calm Storm 的回答的评论(不希望调用 Supplier.get() 两次),那么:

private static final Function<Supplier<X>, X> SUPPLY = new Function<....>() {
    public X apply(Supplier<X> in) {
        // If you will never have a null Supplier, you can skip the test;
        // otherwise, null Supplier will be treated same as one that returns null
        // from get(), i.e. skipped
        return (in == null) ? null : in.get();
    }
}

然后

Iterable<Supplier<X>> suppliers = ... wherever this comes from ...

Iterable<X> supplied = Iterables.transform(suppliers, SUPPLY);

X first = Iterables.find(supplied, Predicates.notNull());

请注意,来自 Iterables.transform() 的 Iterable 是惰性求值的,因此当 Iterables.find() 循环遍历它时,您只求值为就第一个非 null 返回的而言,而且只有一次。

关于java - Google 馆藏供应商和查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2295818/

相关文章:

java - Guava 谓词过滤各种条件,无需匿名类或额外类

Java JFrame 方法 pack()

java - 使用 Java - 每 9 个字符宽行打印四次迭代

java - Elasticsearch-Java 搜索未给出任何结果

java - 如何使用 get 和 put 作为原子操作使并发 HashMap 线程安全?

java - Guava 缓存 : manual management by removal policy

java - 使用 sbt 测试 Guava 代码时出现 IncompatibleClassChangeError

java - Spring Boot端点未经过身份验证

java - 运行 jar 时项目抛出 IOException(未找到文件)

java - Guava 并发教程/代码