我喜欢 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
就此而言),所以我想知道为什么它会丢失。此外,虽然我可以看到有一个 throws 方法的意义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.谓词)