[External] : Re: ReversibleCollection proposal

Henri Tremblay henri.tremblay at gmail.com
Wed Apr 28 13:23:43 UTC 2021


(I think the first version of this message never went through, so here it
goes just in case)

I just read quickly the proposal and it made me think about another common
issue. I wonder if we could tackle it as well.
I will call it the "find the first element when there is only one" problem.
It happens on unordered collections like a HashSet. It forces to do

Set<String> s = new HashSet<>();
if (s.size() == 1) {
   return s.iterator().next();
   // or
   return s.stream().findFirst().get();

Which is a lot of ugliness and object instantiations just to get the first
I would be nice to have a public T findFirst() directly on Iterable<T>.
With a default implementation returning iterator().next(). Things like
ArrayList will want to override will return elementData[0]. It would return
null when the list is empty. Or NoSuchElementException.
It needs to be polished of course but will that be acceptable?


More information about the core-libs-dev mailing list