Java 8 optional

In this article we will look into the java optional that get introduce in Jdk 8. An optional is an class in java.util package and acts as container that can hold both empty and a non-null values. It was introduced as a way to help reduce the number of NullPointerExceptions that occur in Java code.

Java optional

Introduction

Optional is a container that either contains a non-null value or nothing (empty Optional). The Optional class is an implementation of the Null Object pattern, which is a design pattern that was designed to reduce the number of null checks in code. With Optional, you can write cleaner and more concise code that is easier to maintain.

Why optional

We can use the Optional class to wrap our data and avoid the classical null checks and some of the try-catch blocks.
Before Java 8, developers are depended on if-else blocks to act on variables that might hold a null reference.
Often, developers forget the check resulting in the so-called NullPointerException and the application crashes unwantedly during runtime.

Create Optional object

An Optional object cannot be created using its constructor since its constructor is private.
Optional value cannot be changed once created.

Java Optional advantages

  • Null check is not required.
  • No more null pointer exception at run time.
  • Help to write clean code.
  • No more boiler plate code to handle null

Optional object can only be created using its static methods as explained below.
There are 3 method in Optional class to create objects.

  • empty ()
  • of ()
  • ofNullable()

These static methods are used in different scenario for creating object. Let’s discuss.

Create an empty Optional

It is also possible to create an Optional object with empty value using its static empty method as shown below.

Optional<Employee> optional = Optional.empty(employee);

Create an Optional object using of ()

An Optional can be created by calling its static of method supplying it the object that the Optional will hold or the object wrapped by Optional.

  • null value is not allowed in this.
  • It will throw NullpointerException if null is passed
    Employee emp = new Employee ();
    Optional<Employee> optional = Optional.of(emp);

Create an Optional object using ofNullable()

  • ofNullable() is also a static method in Optional class, which accepts an object as argument and creates an Optional object.
  • Null is not allowed.
  • If object is null, it will create and return empty optional object.
Employee emp = new Employee ();
Optional<Employee> optional = Optional.ofNullable(emp);

Some of the Optional method and there us ease with example.To check value is present or not.

isPresent()– returns a Boolean depending on the value’s presence. If the value is present, it returns true otherwise false.
Parameter: No
return type: Boolean
Example

Optional<String> stringOptional = Optional.ofNullable("Hello Optional");
System.out.println(stringOptional.isPresent());

ifPresent()-This method will tell you value is present or not and give addition operation to perform on top of optional objects. If a value is present, performs the given action with the value, otherwise does nothing.
Parameter: Consumer
Throws: NulllPointerException
Example

Optional<String> stringOptional = Optional.ofNullable("Hello Optional");
stringOptional.ifPresent((s -> System.out.println("value is : " + s)));

ifPresentOrElse()-if value is not present and we want to execute something else.
orElseThrow () -If a value is present, returns the value, otherwise throws an exception produced by the exception supplying function.
Filter()-The Optional values are filtered using the filter method that accepts a lambda expression of type Predicate that will store the appropriate check.
map()-The map returns the result of the computation (toLowerCase method) wrapped inside Optional if there’s a value present. Otherwise, it returns an empty Optional.
get()– This method is use to get the value from optional object if present, otherwise a NosuchElementException will be thrown.
orElse()-return value if present, otherwise return the given default value.
–parameter accept of type String
Example

public static String optionalOrElse(){
//Optional<Student> getOptionalStudent = Optional.ofNullable(StudentDataBase.studentSupplier.get());Optional<Student> optionalStudent = Optional.ofNullable(null);
String name =  optionalStudent.map(Student::getName).orElse("Default");
return name;
}

orElseGet() return value if present otherwise, returns the one provided by the given supplier.
parameter: accept of type Supplier
Example

public static String optionalOrElseGet(){
//Optional<Student> getOptionalStudent = Optional.ofNullable(StudentDataBase.studentSupplier.get());
Optional<Student> optionalStudent = Optional.ofNullable(null);
String name =  optionalStudent.map(Student::getName).orElseGet(()->"Default");
return name;
}

orElseThrow()-Return the value of present otherwise throw the exception created by the given supplier.
parameter accept of type Supplier
Example

public static String optionalOrElseThrow(){
//Optional<Student> getOptionalStudent = Optional.ofNullable(StudentDataBase.studentSupplier.get());
Optional<Student> optionalStudent = Optional.ofNullable(null);
String name =  optionalStudent.map(Student::getName).orElseThrow(()->new RuntimeException("No Data available"));
return name;
}

7 thoughts on “Java 8 optional”

Leave a Comment