我喜欢 Google Guava 并且经常使用它,但是我总是发现我在写一种方法。
public static <T> T tryFind(Iterable<T> iterable, Predicate<T> predicate){
for(T t : iterable){
if(predicate.apply(t)){
return t;
}
}
return null;
}
对我来说,这似乎是对
Iterables
的一个非常有用的补充。 (也到 Iterators
就此而言),所以我想知道为什么它不见了。此外,虽然我可以看到抛出 NoSuchElementException
的方法的意义。 ,也许是为了区分找到 null 和没有找到元素,只有当您使用的谓词是时才会出现这种情况public boolean apply(T t){
return t==null;
}
这似乎不是一个常见的情况。
那么为什么 guava 设计者选择了这种行为,而不是如果找不到就返回 null 呢?
这是 [Iterables.find()][1] 的 javadoc
[1]:http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Iterables.html#find(java.lang.Iterable , com.google.common.base.Predicate)
最佳答案
我们正在添加另一个接受默认值的 find() 重载。
关于guava - 为什么 Guava 中的 Iterables.find() 会抛出 NoSuchElementException,而不是返回 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3099188/