Java Iterables.find和Iterators.find-不引发异常,而是获取null
我正在使用google collections并试图找到满足谓词的第一个元素。如果不满足谓词,则返回“null” 不幸的是,当找不到元素时,Iterables.find和Iterators.find会抛出NoTouchElementException 现在,我不得不这样做Java Iterables.find和Iterators.find-不引发异常,而是获取null,java,guava,Java,Guava,我正在使用google collections并试图找到满足谓词的第一个元素。如果不满足谓词,则返回“null” 不幸的是,当找不到元素时,Iterables.find和Iterators.find会抛出NoTouchElementException 现在,我不得不这样做 Object found = null; if ( Iterators.any( newIterator(...) , my_predicate ) { found = Iterators.find( newItera
Object found = null;
if ( Iterators.any( newIterator(...) , my_predicate )
{
found = Iterators.find( newIterator(...), my_predicate )
}
我可以用“try/catch”来包围,并做同样的事情,但对于我的用例,我将遇到许多找不到元素的情况
有没有更简单的方法 听起来您应该使用Iterators.filter,然后在返回的迭代器上检查hasNext的值。我不确定这是否更简单,但至少它避免了异常,只需要对源iterable进行一次传递:
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();
}
public static T findMatchOrNull(迭代器源,谓词pred){
迭代器匹配=迭代器.filter(源,pred);
Iterator padded=Iterators.concat(匹配,Iterators.singletonIterator(null));
返回padded.next();
}
这是作为功能请求提交的:
实际上,我们正在进行这项工作。自Guava 7以来,您可以使用Iterables.find()重载来完成这项工作,该重载采用默认值:
Iterables.find(iterable, predicate, null);