Java 8 - Optional class example

Posted on April 30, 2017


Then java.util.Optional<T> class is a container class which may or not may contain a non-null values. It provides various utility methods to check the presence or absence of an object, which helps to deal with NullPointerException.

The following examples demonstrate how the various methods of the Optional class works in java program.

Java Optional - empty(), of() and ofNullable() methods

Optional.empty() -  Return an empty Optional object.

Optional.of() - Return an Optional object with a non-null value. It will throw NullPointerException if value is null.

Optional.ofNullable() - Return an Optional object with a non-null value. It will return empty Optional object if value is null.

package com.boraji.tutorial;

import java.util.Optional;

public class OptionalExample {
   public static void main(String[] args) {

      // Creating empty Optional object
      Optional<String> string = Optional.empty();
      Optional<Double> decimal = Optional.empty();

      // Creating Optional object
      Optional<String> string2 = Optional.of("Optinal class example");
      Optional<Double> decimal2 = Optional.of(45.51);

      // Creating nullable Optional object
      Optional<String> string3 = Optional.ofNullable(null);
      Optional<Double> decimal3 = Optional.ofNullable(null);
   }
}

Java Optional - isPresent() and get() methods

Optional#isPresent() - Return true if a value is present in the Optional object, otherwise false.

Optional#get() - Return a value from Optional object, if value is present, otherwise throws NoSuchElementException.

package com.boraji.tutorial;

import java.util.Optional;

public class OptionalExample {
   public static void main(String[] args) {

      Optional<String> string = Optional.empty();
      if(string.isPresent()){
         System.out.println(string.get());
      }
      
      Optional<String> string2 = Optional.of("Optinal class example");
      if(string2.isPresent()){
         System.out.println(string2.get());
      }

      Optional<String> string3 = Optional.ofNullable(null);
      if(string3.isPresent()){
         System.out.println(string3.get());
      }
   }
}

Output

Optinal class example

Java Optional - ifPresent() method

Optional#ifPresent() – This method invoke a Consumer if a value is present in Optional object, otherwise do nothing.

package com.boraji.tutorial;

import java.util.Optional;

public class OptionalExample {
   public static void main(String[] args) {

      Optional<String> optional1 = Optional.empty();
      optional1.ifPresent(System.out::println);

      Optional<String> optional2 = Optional.of("Java Optional example");
      optional2.ifPresent(System.out::println);
   }
}

Output

Java Optional example

 

Java Optional - orElse(), orElseGet()  and orElseThrow() methods

Optional#orElse()  - Return a value if present, otherwise return other specified value.

Optional#orElseGet()  - Return a value if present, otherwise invoke a Supplier that return other value.

Optional#orElseThrow()  - Return a value if present, otherwise invoke a Supplier that create and throws an exception.

package com.boraji.tutorial;

import java.util.Optional;

public class OptionalExample {
   public static void main(String[] args) {

      Optional<String> optional1 = Optional.empty();
      Optional<String> optional2 = Optional.of("Java Optional example");

      // Using orElse() method
      String str1 = optional1.orElse("orElse example");
      System.out.println(str1);

      String str2 = optional2.orElse("Optional orElse example");
      System.out.println(str2);

      // Using orElseGet() method
      String str3 = optional1.orElseGet(() -> "orElseGet example");
      System.out.println(str3);
      
      String str4 = optional2.orElseGet(() -> "Optional orElseGet example");
      System.out.println(str4);
      
      //Using orElseThrow() method
      try {
         String str5 = optional1.orElseThrow(()->new Exception("Value is not present in Optional"));
         System.out.println(str5);
      } catch (Exception e) {
         e.printStackTrace();
      }
      
      try {
         String str6 = optional2.orElseThrow(()->new Exception("Value is not present in Optional"));
         System.out.println(str6);
      } catch (Exception e) {
         e.printStackTrace();
      }
      
   }
}

Output

orElse example
Java Optional example
orElseGet example
Java Optional example
java.lang.Exception: Value is not present in Optional
	at com.boraji.tutorial.OptionalExample.lambda$2(OptionalExample.java:27)
	at java.util.Optional.orElseThrow(Unknown Source)
	at com.boraji.tutorial.OptionalExample.main(OptionalExample.java:27)
Java Optional example

Java Optional - filter(), map()  and flatMap() methods

Optional#filter()  - Return an Optional object if a value is present, and matches the given Predicate, otherwise return an empty Optional object.

Optional#map()  - Return an Optional object if a value is present, and applies the given mapping Function to it, otherwise return an empty Optional object.

Optional#flatMap()  - Return an Optional object if a value is present, and applies the provided Optional-bearing mapping Function to it, otherwise return an empty Optional object.

package com.boraji.tutorial;

import java.util.Optional;

public class OptionalExample {
   public static void main(String[] args) {

      Optional<String> optional = Optional.of("Java Optional example");

      // Using filter() method
      Optional<String> optional1 = optional.filter(s -> s.contains("Optional"));
      optional1.ifPresent(System.out::println);

      // Using map() method
      Optional<String> optional2 = optional.map(String::toUpperCase);
      optional2.ifPresent(System.out::println);

      // Using flatMap() method
      Optional<String> optional3 = optional.flatMap(s -> Optional.of(s + " - flatMap() method"));
      optional3.ifPresent(System.out::println);
   }
}

Output

Java Optional example
JAVA OPTIONAL EXAMPLE
Java Optional example - flatMap() method