Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Iterables.find() in Guava throw NoSuchElementException, instead of returning null?

I love Google Guava and use it a lot, but there is one method I always find me writing..

 public static <T> T tryFind(Iterable<T> iterable, Predicate<T> predicate){
     for(T t : iterable){
         if(predicate.apply(t)){
              return t;
         }
     }
     return null;
  }

To me this seems to be a very useful addition to Iterables (also to Iterators for that matter), so I'm wondering why it's missing. Also, while I can see the point of having a method that throws NoSuchElementException, perhaps to distinguish between finding a null and not finding the element, that situation only comes up if the predicate you are using is

public boolean apply(T t){
     return t==null;
}

which doesn't seem to be a common case.

So why did guava designers chose to have this behavior, instead of just returning null if it can't find it?

Here is the javadoc for [Iterables.find()][1]

[1]: http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Iterables.html#find(java.lang.Iterable, com.google.common.base.Predicate)

like image 564
Enno Shioji Avatar asked Jun 23 '10 05:06

Enno Shioji


3 Answers

We're adding another overload of find() which accepts a default value.

like image 182
Kevin Bourrillion Avatar answered Nov 05 '22 07:11

Kevin Bourrillion


Likely because null is a valid return value. Generally speaking, unless there is a good reason to not support null then it should be supported. If it is supported then you have to handle the case where it exists.

like image 33
TofuBeer Avatar answered Nov 05 '22 05:11

TofuBeer


Instead of tryFind() you can use filter and check if it returns an empty collection.

I found that always working with collections is cleaner than directly asking objects.

like image 5
Peter Tillemans Avatar answered Nov 05 '22 07:11

Peter Tillemans