Java9 - Optional Class new methods | Java9 Features

Related posts

In this article, we’ll discuss the enhanced features added to the Optional class in Java 9.

What are the Optional Class Improvements in Java 9?

Java 9 introduced additional features to the existing Optional class (java.util.Optional), including the following methods.

  • stream()
  • ifPresentOrElse()
  • or()

These methods were added to the primitive Optional classes in Java 9:

Java 9 Optional stream() Method Example

The stream() method is used to convert an Optional object to a Stream object.

Java has a robust API for manipulating collection data structures using functional programming classes introduced in version 8.

The stream() method was added to the Optional class to enable sequential processing of Optional data.

Syntax:

public Stream<T> stream()

This method returns a stream containing a value if the value is present; otherwise, it returns an empty stream. It’s particularly useful for iterations involving Optional values.

Let’s see an example of converting a list of strings to uppercase in Java 8 and Java 9.

import java.util.*;
public class Test {
    public static void main(String[] args) {
        List<Optional<String>> listOptionalStrings = new ArrayList<>();
        listOptionalStrings.add(Optional.of("one"));
        listOptionalStrings.add(Optional.of("two"));
        listOptionalStrings.add(Optional.of("three"));
        listOptionalStrings.add(Optional.of("four"));

    }
}

How to Convert a List of Strings to Uppercase List in Java 8

In Java 8, the Optional class provides isPresent and get methods.

During list iteration using streams, we check if the value is present or empty with the isPresent() method, retrieve the element using the get() method, and then map it to a list.

import java.util.*;
import java.util.stream.Collectors;

public class Java8Example {
    public static void main(String[] args) {
        List<Optional<String>> listOptionalStrings = new ArrayList<>();
        listOptionalStrings.add(Optional.of("one"));
        listOptionalStrings.add(Optional.of("two"));
        listOptionalStrings.add(Optional.of("three"));
        listOptionalStrings.add(Optional.of("four"));
        // java8 example
        List<String> stringList = listOptionalStrings.stream().filter(Optional::isPresent).map(Optional::get)
                .map(String::toUpperCase).collect(Collectors.toList());
        stringList.forEach((value) -> {
            System.out.println(value);
        });
    }
}

Similarly, we can achieve the same using the flatMap stream method in Java 9.

Java9 - How to convert String List to Uppercase List

Using optional stream, We will combine isPresent()and get()method with Stream() method

import java.util.*;
import java.util.stream.Collectors;

public class Java9Example {
    public static void main(String[] args) {
        List<Optional<String>> listOptionalStrings = new ArrayList<>();
        listOptionalStrings.add(Optional.of("one"));
        listOptionalStrings.add(Optional.of("two"));
        listOptionalStrings.add(Optional.of("three"));
        listOptionalStrings.add(Optional.of("four"));
        // java8 example
        List<String> stringList = listOptionalStrings.stream().flatMap(Optional::stream).map(String::toUpperCase)
                .collect(Collectors.toList());
        stringList.forEach((value) -> {
            System.out.println(value);
        });
    }
}

The output of the above two examples is the same.

ONE
TWO
THREE
FOUR

Java 9 Optional ifPresentOrElse() Method Example

The ifPresentOrElse() method, introduced in Java 9, applies an action with the value if it is present; otherwise, it returns an empty action.

Syntax:

void ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction);

Here’s an example comparing the if-else logic using Java 8:

import java.util.*;

public class Test {
    public static void main(String[] args) {
        Optional<String> stringOptional = Optional.ofNullable("present");
        if (stringOptional.isPresent()) {
            System.out.println(stringOptional.get());
        } else {
            System.out.println("Default");
        }
    }
}

isPresent() method is used to check if the value is present or not, and this method can also be used to execute a consumer when the value is presented.

Hence, for the isPresent method, There is

  • no else support here.
  • No else support for conditional logic

In Java 9, the ifPresentOrElse() method provides a more concise way to handle such logic:

import java.util.*;

public class ifPresentOrElseExample {
    public static void main(String[] args) {
        Optional<String> stringOptional = Optional.ofNullable("present");
        stringOptional.ifPresentOrElse(value -> System.out.println(value), () -> System.out.println("Default"));

    }
}

Output:

present

Java 9 Optional or() Method

The or() method checks if a value is present, returning an Optional containing the value. If not, it returns the result of applying a Supplier function.

public Optional<T> or(Supplier<? extends Optional<? extends T>> supplier)

In Java 8, the orElse() and orElseGet() methods are used to return a default value when the value is not present.

import java.util.*;

public class Test {
    public static void main(String[] args) {
        Optional<String> emptyOption = Optional.empty();
        Optional<String> strOption = Optional.of("one");
        System.out.println(emptyOption.orElse("defaultvalue")); // Outputs one
        System.out.println(strOption.orElse("defaultvalue")); // defaultvalue is returned

        System.out.println(emptyOption.orElseGet(() -> "optional null orElseGet"));
        System.out.println(strOption.orElseGet(() -> "Optional value orElseGet"));

    }
}

Output:

defaultvalue
one
optional null orElseGet
one

orElse(), orElseGet() method both returns type of the value instead of Optional object.

We need to have an Optional inbuilt type like this method which returns an Optional object.

The or() method in Java 9 provides similar functionality, returning an Optional object:

Syntax:

public Optional<T> or(T value)

or() method provides the implementation for returning Optional object and functionality is same as like orElse(), orElseGet() method.

import java.util.*;

public class Test {
    public static void main(String[] args) {
        Optional<String> emptyOption = Optional.empty();
        Optional<String> strOption = Optional.of("one");
        Optional<String> emptyOptionResult = emptyOption.or(() -> {
            String text = "defaultvalue";
            return Optional.ofNullable(text);
        });
        Optional<String> strOptionResult = strOption.or(() -> {
            String text = "defaultvalue";
            return Optional.ofNullable(text);
        });
        System.out.println(emptyOptionResult);
        System.out.println(strOptionResult);

    }
}

Output:

Optional[defaultvalue]
Optional[one]

Conclusion

This tutorial explored the new methods added to the Optional class in Java 9, providing more concise and functional ways to handle optional values.