Tuesday, August 21, 2018

Java8 - Learn java.util.Optional class with examples

In this Blog post, We are going to learn the Optional class with examples.

Optional Class Basics

java8 features - Java.util.Optional
In Java Applications, Many Developers faces NullPointerException during development. NullPointerException is a runtime exception which breaks the code.
Java8 introduced Optional<T> class to avoid null value checking and NullPointerException.
Optional is a class defined in java.util package since Java8 version
This is used to check the values or object is present or not.
This avoids null checks and NullPointerExceptions. The optional class is a container for holding values
For example, The below function has a parameter with EmpId. This return employee object by making a call to the database with employee Id.
Employee emp=findEmployeeById(1234) { };
System.out.println("Salary "+emp.getSalary());
EmployeeId is 1234. if employee record does not exist in the database with id=1234, Then it returns null object.
emp.getSalary() returns NullPointerException as emp object is null. This is a common problem which developers overlook it and it causes the application to crash it.
With java8, Optional class solves this. We will rewrite the same function as follows
Optional<Employee> emp=findEmployeeById(1234) { };
optional.ifPresent(emp -> {
    System.out.println("Salary= " + emp.getSalary());   
});
Optional has many utility methods to check object is present or not.
Here ifPresent() method checking for the null check. and used the lambda expression in it.
Optional Signature
public final class Optional<T> extends Object
Optional Example
We will see the various usage of optional methods with examples

How to create Empty Optional Instance?

This method returns an empty object. No object existing in it.isPresent() return false and indicate absence of value.
Optional<String> str = Optional.empty();
System.out.println(str.isPresent()); // outputs false

Create an optional non-empty instance?

Optional.of() method creates non null values. if null is passed, NullPointerException is thrown on this line and the Optional object is null.
Optional<String> str = Optional.of("One");
System.out.println(str.isPresent()); // outputs true

Optional ofNullable() method

ofNullable() method accepts null and not null values.
Optional<Object> objOptional= Optional.ofNullable(null);
System.out.println(objOptional.isPresent()); // outputs false
Optional<String> strOptional= Optional.ofNullable("One");
System.out.println(strOptional.isPresent()); // outputs true

Optional isPresent() method usage

isPresent() method returns false - if optional object contains null values, else return true - if contain non null value
Optional<Object> objOptional= Optional.ofNullable(null);
System.out.println(objOptional.isPresent()); // outputs false
Optional<String> strOptional= Optional.ofNullable("One");
System.out.println(strOptional.isPresent()); // outputs true

Optional ifPresent() method

This method calls specific consumer if the value is presented.
Optional<String> str = Optional.of("one");
str.ifPresent(System.out::println);// This will be called  outputs one
Optional<String> str1 = Optional.empty(); 
str1.ifPresent(System.out::println); // This will not be called as no value preseneted in Optional class
}

Optional.get() method

This method return value if presented in an optional container
else throws NoSuchElementException.
Please make sure that before using get() method, first check value is presented or absent using isPresent()
Optional<String> emptyOption = Optional.empty();
Optional<String> strOption = Optional.of("one");
System.out.println( strOption.get());
System.out.println( emptyOption.get());
output is
one
Exception in thread "main" java.util.NoSuchElementException: No value present
 at java.base/java.util.Optional.get(Optional.java:148)
 at org.cloudhadoop.defaultmethods.OptionalDemo.main(OptionalDemo.java:31)

Optional.orElse() method

orElse() method is useful to return default value if Optional object is empty
if the value is presented, return an optional value
Optional<String> str = Optional.of("one"); // Optional contains string value 
System.out.println( str.orElse("defaultvalue")); // Outputs one
Optional<String> str1 = Optional.empty(); // Empty Optional object
System.out.println( str1.orElse("defaultvalue")); // defaultvalue is returned

Optional.orElseGet() method

This method returns value if the value is presented, else the supplier is being called and value is returned it
Optional<String> emptyOption = Optional.empty();
Optional<String> strOption = Optional.of("one");
System.out.println(emptyOption.orElseGet(() -> " optional null orElseGet"));
System.out.println(strOption.orElseGet(() -> "Optional value orElseGet"));
Output is

 optional null orElseGet
one

Optional.orElseThrow method

This method return value, if the value is presented else supplier is being called and throws an exception
Optional<String> emptyOption = Optional.empty();
Optional<String> strOption = Optional.of("one");
try {
    System.out.println( emptyOption.orElseThrow(()->new Exception("Value is not present in Optional")));
 } catch (Exception e) {
  e.printStackTrace();
  }
  try {
          System.out.println(strOption.orElseThrow(()->new Exception("Value is not present in Optional")));
       } catch (Exception e) {
          e.printStackTrace();
}

Output is
java.lang.Exception: Value is not present in Optional
 at org.cloudhadoop.defaultmethods.OptionalDemo.lambda$0(OptionalDemo.java:31)
 at java.base/java.util.Optional.orElseThrow(Optional.java:397)
 at org.cloudhadoop.defaultmethods.OptionalDemo.main(OptionalDemo.java:31)
one

Optional filter() method

This method -
if the value is presented and matches given predicate. returning Optional Object
else returning empty optional object.
Optional<String> strOptional = Optional.of("one two three");
Optional<String> optionPredicate = strOptional.filter(s -> s.contains("one"));
optionPredicate.ifPresent(System.out::println);

Output is
one two three

Optional map() method

if the value is presented. and do the mapping to Function.
else returning empty optional object.
Optional<String> strOptional = Optional.of("ONETWOTHREE");
Optional<String> srOptional1 = strOptional.map(String::toLowerCase);
srOptional1.ifPresent(System.out::println);
Output is
onetwothree

Optional flatMap() method

if value is presented. and do the specified optional mapping to Function.
else returning empty optional object.
Optional strOptional = Optional.of("ONETWOTHREE");
Optional strOptional1 = strOptional.flatMap(str -> Optional.of(str + " - appendthis"));
strOptional1.ifPresent(System.out::println);
Output is
ONETWOTHREE - appendthis

Related article


EmoticonEmoticon