Google Collections供应商和查找

ple*_*dge 1 java guava

我正在寻找一种Google Collections方法,该方法返回一系列不返回null的供应商的第一个结果.

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

Cow*_*wan 5

鉴于你对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();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后

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

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

X first = Iterables.find(supplied, Predicates.notNull());
Run Code Online (Sandbox Code Playgroud)

请注意,出来的Iterable Iterables.transform()是懒惰评估的,因此作为Iterables.find()循环,你只评估第一个非null重复的,而且只评估一次.