Java9 - Optional Class new methods | Java9 Features

Related posts

In this article post, We are going to discuss enhanced features added to the java9 Optional class.

What are Optional Class Improvements in Java 9?

Added a few more features to the existing Optional class in java9. java.util.Optional has below methods.

  1. stream()
  2. ifPresentOrElse()
  3. or()

These methods are added to below primitive Optional classes in java9

Java9 Optional Stream() method example

Stream(a) method used to convert Optional Object to Stream Object.

Java has a good API for the manipulation of collection data structures using functional programming classes introduced version 8. Stream() method is added in Optional Class to make sequential processing of Optional data API.

Syntax:

public Stream<T> stream()

This method return stream that contains a value, if the value is present else returns an empty Stream.

This is very useful when you are doing iterations with Optional values.

Let us see an example to convert a list of strings to upper case in Java 8 and Java 9.
For example, Create a List of strings as follows.

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 List of strings to Uppercase List in java 8

In Java8, Optional class has isPresent and get methods

During the stream of list iteration, we are checking the isPresent() method for not null/empty and retrieving the element using the get() method and map to 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 do the same using flatMap stream method in java9 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

Java9 Optional ifPresentOrElse() method example

Optional introduced ifPresentOrElse() method checks - if value is present, apply action with value, else return empty action.
Syntax

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

Here is an example of if-else logic using java8 version

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

with java9, ifPresentOrElse() method is used to have if and else 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

Or() method checks, if value is present, return option contains value.
Else, returns Optional applies to Supplier function.

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

with java8, Optional orElse(), orElseGet() method is used to return default value when value is not presented or empty.

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.

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

In this tutorial, Learned new methods added to the Optional class in java 9.