我正在使用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)