BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Java 8 Optional Class

By Chaitanya Singh | Filed Under: java

In Java 8, we have a newly introduced Optional class in java.util package. This class is introduced to avoid NullPointerException that we frequently encounters if we do not perform null checks in our code. Using this class we can easily check whether a variable has null value or not and by doing this we can avoid the NullPointerException. In this guide, we will see how to work with Optional class and the usage of various methods of this class.

Before we see the example of Optional class, lets see what happens when we don’t use Optional class and do not perform null check.

Java Example: Without using Optional class

In this example, we didn’t assign the value to the String str and we are trying to get the substring out of it. Since there is no value present in the str, the program is throwing NullPointerException.

public class Example {  
    public static void main(String[] args) {  
    	String[] str = new String[10];   
        //Getting the substring
        String str2 = str[9].substring(2, 5);
        //Displaying substring
        System.out.print(str2);  
    }  
}

Output:

Exception in thread "main" java.lang.NullPointerException
at Example.main(Example.java:5)

Solution: Using Optional Class

Optional.ofNullable() method of the Optional class, returns a Non-empty Optional if the given object has a value, otherwise it returns an empty Optional.
We can check whether the returned Optional value is empty or non-empty using the isPresent() method.

//Importing Optional class
import java.util.Optional; 
public class Example { 
   public static void main(String[] args) {    
      String[] str = new String[10];     
      Optional<String> isNull = Optional.ofNullable(str[9]);        
      if(isNull.isPresent()){     
         //Getting the substring           
         String str2 = str[9].substring(2, 5);          
         //Displaying substring           
         System.out.print("Substring is: "+ str2);       
      }     
      else{      
         System.out.println("Cannot get the substring from an empty string");     
      }                
      str[9] = "AgraIsCool";       
      Optional<String> isNull2 = Optional.ofNullable(str[9]);       
      if(isNull2.isPresent()){        
         //Getting the substring            
         String str2 = str[9].substring(2, 5);            
         //Displaying substring           
         System.out.print("Substring is: "+ str2);          
      }         
      else{         
         System.out.println("Cannot get the substring from an empty string");         
      }    
   }  
}

Output:

Cannot get the substring from an empty string
Substring is: raI

Example: Optional isPresent() vs ifPresent() methods

In the above example, we have seen that by using isPresent() method we can check whether the particular Optional object(or instance) is empty or no-empty.
There is another method present in the Optional class, which only executes if the given Optional object is non-empty, the method is ifPresent(). Lets see an example to understand the difference.

//Importing Optional class
import java.util.Optional;
   public class Example {  
      public static void main(String[] args) {
         //Creating Optional object from a String
         Optional<String> GOT = Optional.of("Game of Thrones");        
         //Optional.empty() creates an empty Optional object        
         Optional<String> nothing = Optional.empty();
         /* isPresent() method: Checks whether the given Optional         
          * Object is empty or not.         
          */        
         if (GOT.isPresent()) {          
            System.out.println("Watching Game of Thrones");       
         } 
         else {            
            System.out.println("I am getting Bored");      
         }
         /* ifPresent() method: It executes only if the given Optional         
          * object is non-empty.         
          */        
         //This will print as the GOT is non-empty        
         GOT.ifPresent(s -> System.out.println("Watching GOT is fun!"));                
         //This will not print as the nothing is empty        
         nothing.ifPresent(s -> System.out.println("I prefer getting bored"));
   }
}

Output:

Watching Game of Thrones
Watching GOT is fun!

Java 8 – Optional orElse() and orElseGet() methods

These two methods orElse() and orElseGet() returns the value of Optional Object if it is no empty, if the object is empty then it returns the default value passed to this method as an argument.

//Importing Optional class
import java.util.Optional;
   public class Example {  
      public static void main(String[] args) {
         //Creating Optional object from a String
         Optional<String> GOT = Optional.of("Game of Thrones");        
         //Optional.empty() creates an empty Optional object        
         Optional<String> nothing = Optional.empty();

         //orElse() method
         System.out.println(GOT.orElse("Default Value")); 
         System.out.println(nothing.orElse("Default Value")); 

         //orElseGet() method
         System.out.println(GOT.orElseGet(() -> "Default Value")); 
         System.out.println(nothing.orElseGet(() -> "Default Value")); 

    }
}

Output:

Game of Thrones
Default Value
Game of Thrones
Default Value

Java 8 – Optional.map and Optional.flatMap

In this example, we will see how Optional works with map and flatMap.

//Importing Optional class
import java.util.Optional; 
public class Example {   
   public static void main(String[] args) {
      //Creating Optional object from a String       
      Optional<String> GOT = Optional.of("Game of Thrones");       
      //Optional.empty() creates an empty Optional object       
      Optional<String> nothing = Optional.empty();
      System.out.println(GOT.map(String::toLowerCase));        
      System.out.println(nothing.map(String::toLowerCase));
      Optional<Optional<String>> anotherOptional = Optional.of(Optional.of("BreakingBad"));        
      System.out.println("Value of Optional object"+anotherOptional);        
      System.out.println("Optional.map: "             
          +anotherOptional.map(gender -> gender.map(String::toUpperCase)));        
      //Optional<Optional<String>>    -> flatMap -> Optional<String>        
      System.out.println("Optional.flatMap: "            
          +anotherOptional.flatMap(gender -> gender.map(String::toUpperCase)));
   }
}

Output:

Optional[game of thrones]
Optional.empty
Value of Optional objectOptional[Optional[BreakingBad]]
Optional.map: Optional[Optional[BREAKINGBAD]]
Optional.flatMap: Optional[BREAKINGBAD]

Example: Optional with filter

In this example, we will see how Optional works with filter. To read about filters refer this guide: Java filters.
More tutorials on Filters:

  1. Java – Filter a Map
  2. Filter null values from a Stream in Java
//Importing Optional class
import java.util.Optional; 
public class Example {  
   public static void main(String[] args) {
      //Creating Optional object from a String       
      Optional<String> GOT = Optional.of("Game of Thrones");              
      /* Filter returns an empty Optional instance if the output doesn't         
       * contain any value, else it returns the Optional object of the          
       * given value.         
       */        
      System.out.println(GOT.filter(s -> s.equals("GAME OF THRONES")));         
      System.out.println(GOT.filter(s -> s.equalsIgnoreCase("GAME OF THRONES")));
   }
}

Output:

Optional.empty
Optional[Game of Thrones]

References:
Java 8 – Optional class JavaDoc

❮ PreviousNext ❯

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap