Reputation: 3434
I'm using google-collections and trying to find the first element that satisfies Predicate if not, return me 'null'.
Unfortunately, Iterables.find and Iterators.find throws NoSuchElementException when no element is found.
Now, I am forced to do
Object found = null;
if ( Iterators.any( newIterator(...) , my_predicate )
{
found = Iterators.find( newIterator(...), my_predicate )
}
I can surround by 'try/catch' and do the same thing but for my use-cases, I am going to encounter many cases where no-element is found.
Is there a simpler way of doing this?
Upvotes: 8
Views: 5404
Reputation: 12692
Since Guava 7, you can do this using the Iterables.find() overload that takes a default value:
Iterables.find(iterable, predicate, null);
Upvotes: 13
Reputation: 40851
This was filed as a feature request:
http://code.google.com/p/guava-libraries/issues/detail?id=217
We are actually in progress on it.
Upvotes: 2
Reputation: 48629
I'm not sure if this qualifies as simpler, but at least it avoids exceptions and requires only one pass over the source 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();
}
Upvotes: 0
Reputation: 2832
It sounds like you should be using Iterators.filter, then checking the value of hasNext on the returned iterator.
Upvotes: 5