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

Paul Sandoz paul.sandoz at oracle.com
Wed Jan 31 22:02:13 UTC 2018


See also Stream.findFirst and findAny. Stream is the place we have and I think we should primarily focus effort on rather than Iterable for such features.

I believe a related feature some have requested is the ability to obtain an only, or at most, one element. On Stream this might manifest as:

  T findOne(); 
  Optional<T> findAtMostOne(); 
  // See Guava’s MoreCollectors/onlyElement,toOptional [1]

which might differ in terms of exceptions thrown compared to other terminal operations.

Paul.

[1] https://google.github.io/guava/releases/21.0/api/docs/com/google/common/collect/MoreCollectors.html#onlyElement-- <https://google.github.io/guava/releases/21.0/api/docs/com/google/common/collect/MoreCollectors.html#onlyElement-->


> On Jan 30, 2018, at 10:09 PM, Dave Brosius <dbrosius at mebigfatguy.com> wrote:
> 
> 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