You're missing the main point.
Optional is designed to be a container of data which can never be null
by itself and which is safe to interact with.
Optional is not intended to be a substitution for null-checks. It's mean to represent a nullable return value and should not be creating in order to hide null-checks or chain methods on it (more on that, see here and here).
If you need to validate that something is not null
you can use method Objects#requireNonNull()
and it's flavors or explicit null-check.
The idea behind the optional, is that serves as a box for a value, and you can do whole lot of staff with it without caring if the box empty or not. Optional offers you methods to filter to the value inside the box filter()
, to replace an empty box with another box or()
, to transform the value inside the box map()
, etc. And all these actions can be done by chaining the methods fluently without opening the box.
Methods isNull()
/isNotNull()
are not suitable for the Optional API because they contradict its design goal, which to provide a limited mechanism for representing a nullable return value and a mean of interaction with the target value (around which optional is wrapped) in a simple and fluent way regardless whether its value is null
or not.
Note, that checks isPresent()
(JDK 8) and isEmpty()
(JDK 11) exist as a last resort. Be attentive when you're using them, because most likely you're not leveraging Optional to its full power.
Also, note that wrapping Optional
around a Collection
or an array doesn't make sense because they are container of data as well (like optional) and might be empty as well, which represents the absents of data.
Doing something like this is redundant and inconvenient.
Optional<List<String>> optional = Optional.of(new ArrayList<>());
When a collection is not null
, which should be the case because keeping nullable collections is an antipattern, Collection.isEmpty()
is sufficient to check if the data is present. Meanwhile, when you have optional wrapped around collection, the presence of collection inside the optional doesn't means that the actual data is exists.