Iterables.find和Iterators.find - 而不是抛出异常,收到null
题
我使用的是谷歌的集合,并试图找到的第一个元素满足谓词如果没有,还给我“空”。
不幸的是,Iterables.find和Iterators.find抛出NoSuchElementException异常时没有元件被发现。
现在,我不得不这样做。
Object found = null;
if ( Iterators.any( newIterator(...) , my_predicate )
{
found = Iterators.find( newIterator(...), my_predicate )
}
我可以用“try / catch语句”包围并做同样的事情,但对我的使用情况,我会遇到这样的情形没有元素被发现的许多情况。
是否有这样做的一个简单的方法?
解决方案
听起来你应该使用Iterators.filter,然后检查hasNext对返回的迭代的值。
其他提示
自番石榴7,则可以做到这一点使用Iterables.find()过载,需要一个默认值:
Iterables.find(iterable, predicate, null);
我不知道这是否有资格作为简单的,但至少它避免了异常,只需要一个在源迭代通:
public static <T> T findMatchOrNull(Iterator<T> source, Predicate<T> pred) {
Iterator<T> matching = Iterators.filter(source, pred);
Iterator<T> padded = Iterators.concat(matching, Iterators.<T>singletonIterator(null));
return padded.next();
}
不隶属于 StackOverflow