2010-03-30 39 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);