1. Overview

Every Java coder is familiar with NullPointerException. And it is very hard to avoid it without using too many null checks. Java 8 Optional Class is a new feature of the most awaited major release of Java Programming language.

Optional is a container object which contains a not-null object. It can help in writing a clean and neat code without using multiple null check statements. By using an Optional class, we can use alternate values to return or alternate code to run. By use of Optional Class, the code is more readable because the facts which are hidden are now visible to the developer.

2. Development Environment

Java: Oracle JDK 1.8
IDE: IntelliJ

3. Advantages of Java 8 Optional Class

  • Null checks statement are not required to put in the code.
  • We can develop and execute clean and neat APIs because of removing extra Null checks.
  • At runtime, there is no more NullPointerException.

4. Optional Class Method With Example

The optional class is part of the java. util package, so we have to use import java.util.Optional;

There are the following methods are provides the Java 8 Optional class.

Optional class  of(), ofNullable(), empty(), get() methods

Of()

Returns an Optional with value which is specified.

ofNullable()

Returns an Optional with value which is specified only if the value is present, otherwise returns empty optional class.

Empty()

This method creates an empty Optional object.

Get()

If a value is present then returns a specific value, otherwise throws NoSuchElementException.

Example of Optional Class  Methods

import java.util.Optional;
public class OptionalDemoExample  {
    public static void main(String[] args) {
        //of() method of optional class
        Optional<String> contact = Optional.of("PHONE");
        Optional<String> contact1 = Optional.of("MAIL");
        String result1 = "Yes";
        String result2 = null;
        System.out.println("Optional value:" + contact);
        System.out.println("Optional value:" + contact1);
        //get() method of optional class
        System.out.println("Optional value: contact value : " + contact.get());
        System.out.println("Optional value: contact1 value : " + contact1.get());
        //empty() methodof optional class
        System.out.println("Empty Optional class: " + Optional.empty());
        //ofNullable method of optional class
        System.out.println("ofNullable Optional class: " + Optional.ofNullable(result1));
        System.out.println("ofNullable Empty Optional class: " + Optional.ofNullable(result2));
    }
}
Output:
     Optional value:Optional[PHONE]
     Optional value:Optional[MAIL]
     Optional value: contact value : PHONE
     Optional value: contact1 value : MAIL
     Empty Optional class: Optional.empty
     ofNullable Optional class: Optional[Yes]
     ofNullable Empty Optional class: Optional.empty

 

  Optional class Map() and flatMap() methods

Map()

If a value is present, then apply the mapping function to it, and if the value is not present it will return empty optional class.

flatMap()

If a value is present, then apply the Optional-bearing mapping function to it, and if the value is not present it will return empty optional class.

Example of Optional Class  Methods

import java.util.Optional;
public class OptionalMapExample  {
    public static void main(String[] args) {
        Optional<String> contact = Optional.of("phone");
        Optional<String> emptyContact = Optional.empty();
        System.out.println("Optional class: " + contact.map(String::toUpperCase));
        System.out.println("Empty Optional class: " emptyContact.map(String::toUpperCase));
        Optional<Optional<String>> OptionalContact = Optional.of(Optional.of("phone"));
        System.out.println("Optional value : " + OptionalContact);
        System.out.println("Optional.map value : " + OptionalContact.map(contactt ->    contactt.map(String::toUpperCase)));
        System.out.println("Optional.flatMap value : " + OptionalContact.flatMap(contactt -> contactt.map(String::toUpperCase)));
    }
}
Output:
     Optional class: Optional[PHONE]
     Empty Optional class: Optional.empty
     Optional value : Optional[Optional[phone]]
     Optional.map value : Optional[Optional[PHONE]]
     Optional.flatMap value : Optional[PHONE]

Optional Class filter() Methods

Filter()

If a value is present and the value matches a given condition then it gives result and if the condition does not match, then returns an empty Optional class.

Example of Optional class filter() method

import java.util.Optional;
public class OptionalFilterExample  {
    public static void main(String[] args) {
        Optional<String> contact = Optional.of("PHONE");
        Optional<String> contact1 = Optional.empty();
        //Filter() method of Optional class
        System.out.println(contact.filter(c -> c.equals("phone")));
        System.out.println(contact.filter(c -> c.equalsIgnoreCase("PHONE")));
        System.out.println(contact1.filter(c -> c.equalsIgnoreCase("PHONE"))); 
    }
}
OUTPUT:
     Optional.empty
     Optional[PHONE]
     Optional.empty

Optional class method isPresent() and ifPresent()

isPresent()

it gives result if the value is present othervise result will not display.

ifPresent()

perform given action if the value is available otherwise returns false.

Example of Optional Class above methods

import java.util.Optional;
public class OptionalIfExample  {
    public static void main(String[] args) {
        Optional<String> contact = Optional.of("PHONE");
        Optional<String> emptyContact= Optional.empty();
        if (contact.isPresent()) {
            System.out.println("contact is available.");
        } else {
            System.out.println("contact is not available.");
        }
        //if the condition is true output is display
        contact.ifPresent(c -> System.out.println("value is available in contact option."));
        //if the condition failed output is not display
        emptyContact.ifPresent(g -> System.out.println("value is not available in contact option."));
    }
}
Output:
     contact is available.
     value is available in contact option.

Optional class  orElse() and orElseGet() methods

orElse()

Returns the value if present otherwise returns other value.

orElseGet()

Returns the value if present Otherwise returns default value.

Example of Optional Class above method

import java.util.Optional;
public class OptionalOrElseExample  {
    public static void main(String[] args) {
        Optional<String> contact = Optional.of("PHONE");
        Optional<String> emptyContact = Optional.empty();
        System.out.println(contact.orElse("Empty Contact"));
        System.out.println(emptyContact.orElse("Empty Contact"));
        System.out.println(contact.orElseGet(() -> "Empty Contact"));
        System.out.println(emptyContact.orElseGet(() -> "Empty Contact"));
    }
}
Output:
     PHONE
     Empty Contact
     PHONE
     Empty Contact

5. Conclusion

By using an optional class we can write clean and neat API. This class has various method to handle the value as ‘available ’ or ‘not available’. So it is better to use an optional class rather than using too many null checks.

 

References: – Oracle Documents

Was this post helpful?

Leave a Reply

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