Java Optional class

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Java Optional Class

Java introduced a new class Optional in jdk8. It is a public final class and used to deal with NullPointerException in Java application. You must import java.util package to use this class. It provides methods which are used to check the presence of value for particular variable.

Java Optional Class Methods

Methods

Description

public static Optional empty()

It returns an empty Optional object. No value is present for this Optional.

public static Optional of(T value)

It returns an Optional with the specified present non-null value.

public static Optional ofNullable(T value)

It returns an Optional describing the specified value, if non-null, otherwise returns an empty Optional.

public T get()

If a value is present in this Optional, returns the value, otherwise throws NoSuchElementException.

public boolean isPresent()

It returns true if there is a value present, otherwise false.

public void ifPresent(Consumer consumer)

If a value is present, invoke the specified consumer with the value, otherwise do nothing.

public Optional filter(Predicate predicate)

If a value is present, and the value matches the given predicate, return an Optional describing the value, otherwise return an empty Optional.

public Optional map(Function mapper)

If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional.

public Optional flatMap(Function mapper)

If a value is present, apply the provided Optional-bearing mapping function to it, return that result, otherwise return an empty Optional.

public T orElse(T other)

It returns the value if present, otherwise returns other.

public T orElseGet(Supplier other)

It returns the value if present, otherwise invoke other and return the result of that invocation.

public T orElseThrow(Supplier exceptionSupplier) throws X extends Throwable

It returns the contained value, if present, otherwise throw an exception to be created by the provided supplier.

public boolean equals(Object obj)

Indicates whether some other object is "equal to" this Optional or not. The other object is considered equal if:

  • It is also an Optional and;

  • Both instances have no value present or;

  • the present values are "equal to" each other via equals().

public int hashCode()

It returns the hash code value of the present value, if any, or returns 0 (zero) if no value is present.

public String toString()

It returns a non-empty string representation of this Optional suitable for debugging. The exact presentation format is unspecified and may vary between implementations and versions.

Example: Java Program without using Optional

In the following example, we are not using Optional class. This program terminates abnormally and throws a nullPointerException.

  1. public class OptionalExample {  
  2.     public static void main(String[] args) {  
  3.         String[] str = new String[10];  
  4.         String lowercaseString = str[5].toLowerCase();  
  5.         System.out.print(lowercaseString);  
  6.     }  
  7. }  

Output:

Exception in thread "main" java.lang.NullPointerException
	at lambdaExample.OptionalExample.main(OptionalExample.java:6)

To avoid the abnormal termination, we use Optional class. In the following example, we are using Optional. So, our program can execute without crashing.


Java Optional Example: If Value is not Present

  1. import java.util.Optional;  
  2. public class OptionalExample {  
  3.     public static void main(String[] args) {  
  4.         String[] str = new String[10];  
  5.         Optional<String> checkNull = Optional.ofNullable(str[5]);  
  6.         if(checkNull.isPresent()){  // check for value is present or not  
  7.             String lowercaseString = str[5].toLowerCase();  
  8.             System.out.print(lowercaseString);  
  9.         }else  
  10.             System.out.println("string value is not present");  
  11.     }  
  12. }  

Output:

string value is not present

Java Optional Example: If Value is Present

 
  1. import java.util.Optional;  
  2. public class OptionalExample {  
  3.     public static void main(String[] args) {  
  4.         String[] str = new String[10];        
  5.         str[5] = "JAVA OPTIONAL CLASS EXAMPLE";// Setting value for 5th index  
  6.         Optional<String> checkNull = Optional.ofNullable(str[5]);  
  7.         if(checkNull.isPresent()){  // It Checks, value is present or not  
  8.             String lowercaseString = str[5].toLowerCase();  
  9.             System.out.print(lowercaseString);  
  10.         }else  
  11.             System.out.println("String value is not present");  
  12.     }  
  13. }  

Output:

java optional class example

Another Java Optional Example

 
  1. import java.util.Optional;  
  2. public class OptionalExample {  
  3.     public static void main(String[] args) {  
  4.         String[] str = new String[10];        
  5.         str[5] = "JAVA OPTIONAL CLASS EXAMPLE";  // Setting value for 5th index  
  6.         Optional<String> checkNull = Optional.ofNullable(str[5]);  
  7.         checkNull.ifPresent(System.out::println);   // printing value by using method reference  
  8.         System.out.println(checkNull.get());    // printing value by using get method  
  9.         System.out.println(str[5].toLowerCase());     
  10.     }  
  11. }  

Output:

JAVA OPTIONAL CLASS EXAMPLE
JAVA OPTIONAL CLASS EXAMPLE
java optional class example

Java Optional Methods Example

 
  1. import java.util.Optional;  
  2. public class OptionalExample {  
  3.     public static void main(String[] args) {  
  4.         String[] str = new String[10];        
  5.         str[5] = "JAVA OPTIONAL CLASS EXAMPLE";  // Setting value for 5th index  
  6.         // It returns an empty instance of Optional class   
  7.         Optional<String> empty = Optional.empty();  
  8.         System.out.println(empty);  
  9.         // It returns a non-empty Optional  
  10.         Optional<String> value = Optional.of(str[5]);  
  11.         // If value is present, it returns an Optional otherwise returns an empty Optional  
  12.         System.out.println("Filtered value: "+value.filter((s)->s.equals("Abc")));  
  13.         System.out.println("Filtered value: "+value.filter((s)->s.equals("JAVA OPTIONAL CLASS EXAMPLE")));  
  14.         // It returns value of an Optional. if value is not present, it throws an NoSuchElementException    
  15.         System.out.println("Getting value: "+value.get());  
  16.         // It returns hashCode of the value  
  17.         System.out.println("Getting hashCode: "+value.hashCode());  
  18.         // It returns true if value is present, otherwise false  
  19.         System.out.println("Is value present: "+value.isPresent());  
  20.         // It returns non-empty Optional if value is present, otherwise returns an empty Optional  
  21.         System.out.println("Nullable Optional: "+Optional.ofNullable(str[5]));  
  22.         // It returns value if available, otherwise returns specified value,  
  23.         System.out.println("orElse: "+value.orElse("Value is not present"));  
  24.         System.out.println("orElse: "+empty.orElse("Value is not present"));  
  25.         value.ifPresent(System.out::println);   // printing value by using method reference   
  26.     }  
  27. }  

Output:

Optional.empty
Filtered value: Optional.empty
Filtered value: Optional[JAVA OPTIONAL CLASS EXAMPLE]
Getting value: JAVA OPTIONAL CLASS EXAMPLE
Getting hashCode: -619947648
Is value present: true
Nullable Optional: Optional[JAVA OPTIONAL CLASS EXAMPLE]
orElse: JAVA OPTIONAL CLASS EXAMPLE
orElse: Value is not present
JAVA OPTIONAL CLASS EXAMPLE