Iterables.find and Iterators.find - instead of throwing exception, get null

Posted by mjlee on Stack Overflow See other posts from Stack Overflow or by mjlee
Published on 2010-03-30T05:32:52Z Indexed on 2010/03/30 5:43 UTC
Read the original article Hit count: 298

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about java

Related posts about google-collections