Open trtrmitya opened 5 years ago
We have MoreCollectors.onlyOne()
which produces empty Optional unless exactly one element is returned (and it was actually introduced before Guava). I'm not quite sure that throwing the exception if you have more than one element is better. If you want to distinguish between zero and more than one case, you'll need to catch and handle exception somehow which is ugly. If any non-one case is exceptional, then collect(onlyOne()).get()
would work.
Does onlyOne()
terminate the stream when a second element is encountered, or will it silently consume and reject all the discarded elements?
... just checked the code. It does terminate the stream processing. Nice!
Thanks for your comments.
While indeed collect(onlyOne()).get()
will lead to the same result as onlyElement()
, it is just a bit misleading notation for theonlyElement()
concept (and also longer).
Yes, there are cases when we want to get an exception (to catch it later or to terminate the thread) if the condition does not hold. For example, when I select a row from DB using primary key, I want to use toOptional()
and get an exception if there are more that one row returned. Because it means there is something wrong with my schema and I do not want to proceed further.
There are other scenarios in our application when our data enforce some restriction and we use onlyElement()
and expect exception otherwise because it means something is wrong with the data.
I understand that I can code these thing myself using the existing facilities, but since the main goal of StreamEx (as I see it) is to make development using Java streams more pleasant, I see no problem in adding more helpers to make code shorter and more expressive. In my opinion is it better to have rich set of collectors for every occasion rather than provide a minimal required set.
Thanks.
Hello,
Please add two more collectors:
onlyElement if streams has exactly one element, return it; otherwise throw an exception
toOptional return Optional.empty is stream is empty, Optional.of(elem) if streams has exactly one element, and throw an exception otherwise
Names taken from Guava's MoreCollectors.
Alternative good choice for naming is single / singleO.
Thanks!