我正在寻找一种 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/