Note on java.util.functions

David Conrad drconrad at gmail.com
Tue May 22 09:51:46 PDT 2012


On Tue, May 22, 2012 at 10:16 AM, Brian Goetz <brian.goetz at oracle.com>wrote:

> Thanks for reviewing.
>
> > Iterables.getFirst() and Iterators.getFirst() should throw
> > NoSuchElementException if there are no elements, not return null, which
> is
> > a perfectly valid element in some collections. Also, they should just be
> > named first(), IMHO.
>
> Except that is not their intended semantics.  The intended semantics is
> that they be find-first, where "not found" is an expected condition.  One
> possibility for making this clearer is to return something like Guava's
> Option.
>
> Ultimately this comment is indicative of bad naming; obviously "getFirst"
> suggests to you (and probably others) that there must be a first element,
> maybe this should be called "findFirst" or something like that.  It is made
> worse by the fact that getOnly *does* throw.  The assymmetry is deliberate;
> one is a way of asserting the Iterable has exactly one element (getOnly);
> the other is a way of saying "get me the first one if there is any; I don't
> care if there are more."  Both are important use cases, but probably should
> be named differently.
>
>
Ah, okay. It's partly due to their naming but also partly due to the fact
that I needed something similar a short while back. But in my case I
happened to want to return just the smallest (first) item in a
TreeSet<Integer>, and so I had:

    public static <T> T first(Iterable<T> sequence) {
        return sequence.iterator().next();
    }

and:

    System.out.println(first(set));

This actually came up a few times, and so when I saw getFirst() I naturally
thought that's what it was. So maybe you should think about changing the
name, but maybe it was just me.

Cheers,
David


More information about the lambda-dev mailing list