Optional.isEmpty() Available in JDK 11 EA Builds

DZone 's Guide to

Optional.isEmpty() Available in JDK 11 EA Builds

Want to learn more about a new isEmpty() method in JDK 11? Check out this post on early-access builds in JDK 11 and the Optional.isEmpty method.

· Java Zone ·
Free Resource

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 the OpenJDK JDK Early Access Build 23 that I use in this post) now include the isEmpty() method on certain Optional classes, including 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 the 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 that 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()].

java ,jdk 11 ,early access builds ,ea builds ,isempty ,optional

Published at DZone with permission of Dustin Marx , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}