Convenient way of checking equality for Optionals
Would this work?
if (maybeUSB.map(c -> c.getVersion().equals("3.0")).orElse(false))
Optional
implements the equals
method directly:
if (maybeUSB.equals(Optional.ofNullable(testUSB))) {
...
}
(you can also use Objects.equals
rather than calling equals
directly)
EDIT:
If you want both not present to be false, you can do this:
if (maybeUSB.equals(Optional.ofNullable(testUSB)) && maybeUSB.isPresent()) {
...
}
You have many options.
Already noted:
boolean isEqual = maybeFoo.equals(Optional.of(testFoo));
Alternatively:
boolean isEqual = maybeFoo.isPresent() && maybeFoo.get().equals(testFoo);
Or:
boolean isEqual = testFoo.equals(maybeFoo.orElse(null));
These last two do have slightly different semantics: each returns a different value when maybeFoo
is empty and testFoo
is null. It's not clear which is the correct response (which I guess is one reason there's not a standard API method that does this).
You can probably come up with others if you read the Optional
API doc and apply some thought. There's nothing magic that's absent from the docs.
More generally, if you're knocking against this often enough for it to bother you, you might be approaching Optional
with the wrong philosophy.
As I see it, Optional
is about acknowledging that something won't always be present, and that you need (sometimes verbose) code to handle that.
This should be the exception. Wherever possible, try and create variables that can't be null or Optional.empty()
.
In situations where this is unavoidable, embrace the fact that you need extra code.