Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

guava

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?

like image 528
mjlee Avatar asked Mar 30 '10 05:03

mjlee


3 Answers

Since Guava 7, you can do this using the Iterables.find() overload that takes a default value:

Iterables.find(iterable, predicate, null);
like image 98
Etienne Neveu Avatar answered Nov 17 '22 23:11

Etienne Neveu


It sounds like you should be using Iterators.filter, then checking the value of hasNext on the returned iterator.

like image 40
Sean Parsons Avatar answered Nov 18 '22 01:11

Sean Parsons


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.

like image 2
Kevin Bourrillion Avatar answered Nov 18 '22 00:11

Kevin Bourrillion