java.util.Optional Class Deep Dive Tutorial


1. What is Optional in Java

    Optional is a container object which may or may not contain a non-null value.

    The Optional class can be used to represent a value instead of a null reference.


    Optional class was added to java.util package in Java 8.


2. Methods to create Object of Optional class

    There are 3 static that you can make use of to get an Optional object.



    1. public static Optional empty()

      This method returns an empty Optional instance.

      Example:
      Optional<String> optionalString = Optional.empty();
      Optional<Integer> optionalInteger = Optional.empty();
      Optional<Employee> optionalEmployee = Optional.empty();


    2. public static Optional of(T value)

      This method returns an Optional value for the given non-null value.

      It is important to note that the value provided as an argument to this method is non-null, or else you will get a NullPointerException while performing operations on it if the value is null.

      Example:
      String strValue = "Code2care";
      Optional optionalString = Optional.of(strValue);
      
      Integer intValue = 20;
      Optional optionalInteger = Optional.of(intValue);
      
      Employee empValue = new Employee(1, "Sam","IT");
      Optional optionalEmployee = Optional.of(empValue);


    3. public static Optional ofNullable(T value)

      This method returns an Optional for the given value, if it is non-null, or else returns an empty Optional.

      Example:
      String strValue = "Code2care";
      Optional optionalString = Optional.ofNullable(strValue);
      
      Integer intValue = 20;
      Optional optionalInteger = Optional.ofNullable(intValue);
      
      Employee empValue = new Employee(1, "Sam","IT");
      Optional optionalEmployee = Optional.ofNullable(empValue);

3. How to Get Values from an Optional Object

    Below are the methods from the Optional class that you can make use of to get value from an Optional type.



    1. get() Method:

      Use the get() method to retrieve the value if it is present. Note that if the value is absent (empty), it will throw a NoSuchElementException. It's recommended to use this method only when you are certain the value is present.

      Example:
      Optional<String> optionalString = Optional.of("Code2care");
      String value = optionalString.get();


    2. orElse(T defaultValue) Method:

      Use the orElse(T defaultValue) method to get the value if present, or provide a default value if the Optional is empty.

      Example:
      Optional<Integer> optionalInteger = Optional.ofNullable(20);
      Integer value = optionalInteger.orElse(0);


    3. orElseGet(Supplier<? extends T> supplier) Method:

      Use the orElseGet method to get the value if present, or provide a Supplier that generates a default value if the Optional is empty.

      Example:
      Optional<Employee> optionalEmployee = Optional.empty();
      Employee defaultValue = optionalEmployee.orElseGet(() -> new Employee(0, "Default", "DefaultDept"));


    4. orElseThrow() and orElseThrow(Supplier<? extends X> exceptionSupplier) Methods:

      Use orElseThrow() to get the value if present or throw NoSuchElementException if empty.

      Use orElseThrow(Supplier<? extends X> exceptionSupplier) to throw a custom exception if empty.

      Optional<Employee> optionalEmployee = Optional.of(new Employee(1, "Sam", "IT"));
      Employee value = optionalEmployee.orElseThrow();

4. Optional with Lambda and Stream API

  1. Optional with Lambda and Stream:

    You can make use of Lambda expressions and Streams with Optional to express code in a clean way.

    Examples:
    Optional<String> optionalString = Optional.of("Code2care");
    optionalString.ifPresent(value -> System.out.println("Value is present: " + value));
    Optional<Integer> optionalInteger = Optional.ofNullable(20);
    Optional<String> transformedValue = optionalInteger
                                            .filter(value -> value > 10)
                                            .map(value -> "Transformed: " + value);
    Optional<Employee> optionalEmployee = Optional.of(new Employee(1, "Sam", "IT"));
    String department = optionalEmployee
                        .map(Employee::getDepartment)
                        .orElseGet(() -> getDepartmentFromDatabase());


Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap