Possible addition of a default 'getOne' method on Iterable?

Dave Brosius dbrosius at mebigfatguy.com
Wed Jan 31 06:09:44 UTC 2018


Basically, but it's

annoying and ugly to write

most likely sub-optimal

has problems with things like synchronized collections


On 01/31/2018 12:28 AM, Zheka Kozlov wrote:
> Isn't iterable.getOne() the same as iterable.iterator().next()?
>
> 2018-01-31 12:15 GMT+07:00 Dave Brosius <dbrosius at mebigfatguy.com 
> <mailto:dbrosius at mebigfatguy.com>>:
>
>     Greetings,
>
>
>     sorry if this has been asked before, but has there been any
>     consideration for adding a
>
>     default T getOne() {
>
>         Iterator<T> it = iterator();
>         if (!it.hasNext()) {
>             throw new NoSuchElementException();
>         }
>
>         return it.next();
>     }
>
>
>     on the Iterable interface?
>
>
>     It is often the case you have a collection of some sort (un
>     indexed, in this case), where you know there is only one value in
>     the collection, or you know for some attribute of all the objects
>     in the Iterable, all objects can be thought of as the same, and so
>     you just want to get any of the elements.
>
>     Having to craft this iterator code is annoying, and it would be
>     much nicer to be able to do
>
>     String s = mySet.getOne();
>
>     In addition to this, it is likely that most collections could
>     implement getOne() more optimally than using the standard iterator
>     approach.
>
>     Of course i am not stuck on the choice of the name 'getOne'
>     anything would do. examplar() ?  As we know, naming is always the
>     hardest part.
>
>     thoughts?
>     dave
>
>



More information about the core-libs-dev mailing list