Optional.isEmpty() Available in JDK 11 EA Builds

My recently posted question “Optional.isEmpty() Coming to Java?” was prompted by a core-libs-dev mailing list post titled “RFR: 8184693: (opt) add Optional.isEmpty“. The current JDK 11 Early Access builds (such as OpenJDK JDK Early Access Build 23 that I use in this post) now include the isEmpty() method on the “Optional” classes Optional, OptionalDouble, OptionalInt, and OptionalLong. This allows for more fluent expression in cases that formerly relied upon negation of Optional.isPresent() [or !OptionalDouble.isPresent(), !OptionalInt.isPresent(), or !OptionalLong.ifPresent()] as was done previously.

The next simple and contrived code listing demonstrates Optional.isEmpty().


public static void demonstrateOptionalIsEmpty()
{
final Optional<String> middleName = getMiddleName();
if (middleName.isEmpty())
{
out.println("There is no middle name!");
}
}

Although the same functionality that Optional.isEmpty() provides can be achieved with !Optional.isPresent(), there are advantages to having these types of “isEmpty” methods available in the APIs of commonly used collection and data-holding classes. The ! symbol is more easily missed when reading and reviewing code than is an explicitly named method such as “isEmpty().” Having such a method also aligns Optional‘s API for detecting “empty” more closely to that provided by String [String.isEmpty()],Collection [Collection.isEmpty()], and Map [Map.isEmpty()].

%d bloggers like this: