Convenient way of checking equality for Optionals

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.

Leave a Comment

tech