Iterables.find和Iterators.find - 而不是抛出异常,得到null

mjl*_*lee 8 java guava

我正在使用google-collections并尝试找到满足谓词的第一个元素,如果没有,请返回'null'.

不幸的是,当没有找到元素时,Iterables.find和Iterators.find抛出NoSuchElementException.

现在,我被迫做了

Object found = null;
if ( Iterators.any( newIterator(...) , my_predicate )
{
    found = Iterators.find( newIterator(...), my_predicate )
}
Run Code Online (Sandbox Code Playgroud)

我可以通过'try/catch'进行环绕并做同样的事情但是对于我的用例,我会遇到很多没有找到元素的情况.

有更简单的方法吗?

Eti*_*veu 13

从Guava 7开始,您可以使用带有默认值的Iterables.find()重载来执行此操作:

Iterables.find(iterable, predicate, null);
Run Code Online (Sandbox Code Playgroud)


Sea*_*ons 5

听起来你应该使用Iterators.filter,然后在返回的迭代器上检查hasNext的值.