Java 8 Optional using simple example
Java 8 introduced a new container class java.util.Optional<T>. It wraps a single value, if that value is available. If the value is not available an empty optional should be returned. Thus it represents null value with absent value. This class has various utility methods like isPresent() which helps users to avoid making use of null value checks. So instead of returning the value directly, a wrapper object is returned thus users can avoid the null pointer exception.
Consider the Item class-
package com.javainuse.model;
public class Item {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Consider the class ItemProcessor which returns an instance of Item class-
package com.javainuse;
import com.javainuse.model.Item;
public class ItemProcessor {
public Item getItem() {
// Some logic here like webservice calls or db calls
return item;
}
}
When we call the getItem(), the item instance is returned. We first have to check for null else this may cause NullPointerException.
ItemProcessor ip= new ItemProcessor(); Item item=ip.getItem(); if(item!=null) System.out.println(item.getName());
Now lets consider the use of Optional. Instead of item instance we return optional.
package com.javainuse;
import java.util.Optional;
import com.javainuse.model.Item;
public class OptionalItemProcessor {
public Optional<Item> getItem() {
// Some logic here like webservice calls or db calls..
// if item is successfully processed in our logic..then create optional
// using Optional.of(Object)
return Optional.of(item);
// else if no item is returned from our logic then
return Optional.empty();
}
}
Here first check if the optional element is present and only then process it. No null checks are required.
OptionalItemProcessor ip1= new OptionalItemProcessor();
Optional<Item> item=ip1.getItem();
if(!item.isPresent())
{
System.out.println("not present");
}else
System.out.println(item.get().getName());
See Also
Java - PermGen space vs MetaSpace Understand Java 8 Method References using Simple Example Java 8 Lambda Expression- Hello World Example Java 8-Internal vs. External Iteration. Understanding Java 8 Streams using examples.
Popular Posts
1Z0-830 Java SE 21 Developer Certification
Azure AI Foundry Hello World
Azure AI Agent Hello World
Foundry vs Hub Projects
Build Agents with SDK
Bing Web Search Agent
Function Calling Agent
Spring Boot + Azure Key Vault Hello World Example
Spring Boot + Elasticsearch + Azure Key Vault Example
Spring Boot Azure AD (Entra ID) OAuth 2.0 Authentication
Deploy Spring Boot App to Azure App Service
Secure Azure App Service using Azure API Management
Deploy Spring Boot JAR to Azure App Service
Deploy Spring Boot + MySQL to Azure App Service
Spring Boot + Azure Managed Identity Example
Secure Spring Boot Azure Web App with Managed Identity + App Registration
Elasticsearch 8 Security - Integrate Azure AD OIDC