guava - 为什么 Guava 中的 Iterables.find() 会抛出 NoSuchElementException,而不是返回 null?

标签 guava api-design

我喜欢 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/

相关文章:

url - 健康检查是否应该调用其他应用健康检查

python - Tweepy - 排除转推

java - 是否可以将 Guava Cache(或其他库)行为配置为 : If time to reload, 返回上一个条目,在后台重新加载(参见规范)

java - FluentIterable : should limit() be called as soon as possible?

java - Guava 的 ImmutableSet 成员方法是否模仿 java.util.HashSet#contains?

c# - 从自定义模型 Binder 返回 403

lambda - 将 CustomObject 列表转换为 Guava Table 集合,复杂性较低

java - 缓存修改通知?

rest - 一般与特定端点 - Restful API 设计

java - 我应该在接口(interface)中为开发人员方便声明方法吗?