Returning a Value, or a Default, From a Java Optional

Java Optionals are great for giving you flexibility over interacting with values that may not be present, and include a means for more safely retrieving values from nullable types.

For instance, you may want to call a method on a maybe-null object passed into your method, or return a default value:

private static String getName(Principal nullable) {
  Optional<Principal> maybePrincipal = Optional.ofNullable(nullable);
  if (maybePrincipal.isPresent()) {
    return maybePrincipal.get().getName();
  } else {
    return "<unknown>";
  }
}

This is fine, but doesn't follow the functional style that's possible with the Optional class.

What you may want to do instead is the following (linebreaks added for visibility):

private static String getName(Principal nullable) {
  Optional<Principal> maybePrincipal = Optional.ofNullable(nullable);
  return maybePrincipal
    .map(Principal::getName)
    .orElse("<unknown>");
}

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

#blogumentation #java.

This post was filed under articles.

Related Posts

Other posts you may be interested in:

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.