DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Using Python Libraries in Java
  • Designing a Java Connector for Software Integrations
  • How to Convert XLS to XLSX in Java
  • Recurrent Workflows With Cloud Native Dapr Jobs

Trending

  • Designing a Java Connector for Software Integrations
  • Beyond Code Coverage: A Risk-Driven Revolution in Software Testing With Machine Learning
  • Breaking Bottlenecks: Applying the Theory of Constraints to Software Development
  • How Trustworthy Is Big Data?
  1. DZone
  2. Coding
  3. Java
  4. Java 8 Optional: Handling Nulls Properly

Java 8 Optional: Handling Nulls Properly

Let's learn how to use Java 8's Optionals to make your null checks simple and less error-prone!

By 
Yogen Rai user avatar
Yogen Rai
·
Jun. 18, 18 · Tutorial
Likes (51)
Comment
Save
Tweet
Share
217.4K Views

Join the DZone community and get the full member experience.

Join For Free

Java 8 introduced the Optionalclass to make handling of nulls less error-prone. For example, the following program to pick the lucky name has a null check as:

public static final List<String> NAMES = Arrays.asList("Rita", "Gita", "Nita", "Ritesh", "Nitesh", "Ganesh", "Yogen", "Prateema");

public String pickLuckyNameOldWay(final List<String> names, final String startingLetter) {
  String luckyName = null;
  for (String name : names) {
    if (name.startsWith(startingLetter)) {
      luckyName = name;
      break;
    }
  }
  return luckyName != null ? luckyName : "No lucky name found";
}


This null check can be replaced with the Optional  class method isPresent()  as shown below:

public String pickLuckyNameWIsPresent(final List<String> names, final String startingLetter) {
   final Optional<String> luckyName = names.stream().filter(name -> name.startsWith(startingLetter)).findFirst();

   return luckyName.isPresent() ? luckyName.get() : "No lucky name found";
}


However, notice the writing is no easier than:

return luckyName != null ? luckyName : "No lucky name found";


The Optional  class, however, supports other techniques that are superior to checking nulls. The above code can be re-written as below with  orElse()  method as below:

public String pickLuckyNameWOrElse(final List<String> names, final String startingLetter) {    
  final Optional<String> luckyName = names.stream().filter(name -> name.startsWith(startingLetter)).findFirst();    

  return luckyName.orElse("No lucky name found");
}

 

The method orElse()  is invoked with the condition "If X is null, populate X. Return X.", so that the default value can be set if the optional value is not present.

There is another method called the ifPresent(Function). You can use this method to invoke an action and skip the null case completely. For example, the program below prints a message in the case, if the condition is met as:

public static void pickLuckyNameOldWay(final List<String> names, final String startingLetter) {    
  String luckyName = null;    
  for (String name : names) {        
    if (name.startsWith(startingLetter)) {            
      luckyName = name;            
      break;        
    }    
  }    
  if (luckyName != null) {        
    postMessage(luckyName);    
  }
}
public static void postMessage(final String winnerName) {    
  System.out.println(String.format("Congratulations, %s!", winnerName));
}


This can be re-written with ifPresent() , as shown below. in a more intuitive manner, as:

public static void pickLuckyNameNewWay(final List<String> names, final String startingLetter) {
   final Optional<String> luckyName = names.stream().filter(name -> name.startsWith(startingLetter)).findFirst();
   luckyName.ifPresent(OptionalIfPresent::postMessage);
}


If we want to throw an exception in case if no name is found, then it would be something like this:

public String pickLuckyNameOldWay(final List<String> names, final String startingLetter) {    
  String luckyName = null;
  // ... same code here
  if (luckyName == null) {        
    throw new NotFoundException("There is no name starting with letter.");    
  }    
  return luckyName;
}


It can be meaningfully replaced with orElseThrow as:

public String pickLuckyNameWOrElse(final List<String> names, final String startingLetter) {    
  final Optional<String> luckyName = names.stream().filter(name -> name.startsWith(startingLetter)).findFirst();    
  return luckyName.orElseThrow(() -> new NotFoundException("There is no name starting with letter."));
}


There are other many more methods in the Optional  class to handle null  in more proper way. You can go through the Optional in Java 8 cheat sheet.

As always, if you want to look into the source code for the example presented above, they are available on GitHub.

Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Using Python Libraries in Java
  • Designing a Java Connector for Software Integrations
  • How to Convert XLS to XLSX in Java
  • Recurrent Workflows With Cloud Native Dapr Jobs

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!