I encounter a specific use case where I often need to wrap objects in Optional
if they are empty. Take a look at this code:
List<AbstractCorporateAction> cas = stream.toList();
if (cas.isEmpty()) return Optional.empty();
else return Optional.of(cas);
I check whether the list is empty or not and if it is indeed empty, I return an empty optional and if not, I wrap it. The reason for this is sometimes I get a null value for list itself and sometimes I get an actual list but it is empty.
With this approach, I do not need to double-check the underlying list when the returned optional itself is empty.
But for different data structures, the implementation varies. Is there a built-in way with third party libraries to achieve this?
The closest I got is from Guava.MoreObjects#isEmpty
but it only checks whether the object is empty or not and does not return an optional in case it is empty.
I could write my own cover for this, but I'm looking for a professional, reliable approach to achieve the required functionality.
>` is really any better for your use-case than a simple `List`. What's the semantic difference between an absent Optional and an Optional that holds an empty list? If there's no difference (which your question seems to imply), then there's one unnecessary and potentially bug-causing state in this type that you don't need and should make impossible. A simple `List` can already be empty or contain content.
– Joachim Sauer Jul 21 '22 at 08:00>` is there a defined *meaning* of it being absent versus it being present and containing a list that happens to be empty? Does your code handle those two cases differently? Would one of them be considered a bug? Does it make sense to make that distinction?
– Joachim Sauer Jul 21 '22 at 09:09