2010-03-30 49 views
8

我使用谷歌集合,并试图找到第一个满足谓词的元素,如果没有,返回我'null'。Iterables.find和Iterators.find - 而不是抛出异常,得到空

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

现在,我不得不做

Object found = null; 
if (Iterators.any(newIterator(...) , my_predicate) 
{ 
    found = Iterators.find(newIterator(...), my_predicate) 
} 

我可以用“try/catch语句”,做同样的事情,但对我的使用情况,我会遇到很多情况下,没有元素环绕被发现。

有没有更简单的方法呢?

回答

5

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

0

我不知道这是否有资格作为简单的,但至少它避免了异常,只需要一个传过来的源迭代:

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(); 
} 
12

由于番石榴7,你可以做到这一点使用Iterables.find()重载需要一个默认值:

Iterables.find(iterable, predicate, null);