Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

Get the Edge with a Professional Java IDE. 30-day free trial.

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()].

Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.

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

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}