ReversibleCollection proposal
Henri Tremblay
henri.tremblay at gmail.com
Tue Apr 27 15:08:39 UTC 2021
Hi,
Not sure if this will end up in the right mailing list thread but let's see.
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 instantiation just to get the first
element.
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?
Thanks,
Henri
More information about the core-libs-dev
mailing list