Java 9 - Optional Class Improvements with Examples

Optional Class was introduced in Java 8 to avoid null checks and NullPointerException issues. In java 9, three new methods are added to improve its functionality.
  • stream()
  • ifPresentOrElse()
  • or()
Let's discuss each of these methods with an example.
Learn Java 8 at https://www.javaguides.net/p/java-8.html

Optional stream() method

If a value is present, it returns a sequential Stream containing only that value, otherwise returns an empty Stream.
Example:
package net.javaguides.corejava.java9;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Demonstrates Java9 Optional Class improvements
 * @author Ramesh Fadatare
 *
 */
public class Java9OptionalClass {
    public static void main(String[] args) {
        List < Optional < String >> list = List.of(
            Optional.empty(),
            Optional.of("ABC"),
            Optional.empty(),
            Optional.of("XYZ"));

        // filter the list based to print non-empty values

        // if optional is non-empty, get the value in stream, otherwise return empty
        List < String > filteredList = list.stream()
            .flatMap(o - > o.isPresent() ? Stream.of(o.get()) : Stream.empty())
            .collect(Collectors.toList());

        // Optional::stream method will return a stream of either one
        // or zero element if data is present or not.
        List < String > filteredListJava9 = list.stream()
            .flatMap(Optional::stream).collect(Collectors.toList());

        System.out.println(filteredList);
        System.out.println(filteredListJava9);
    }
}
Output:
[ABC, XYZ]
[ABC, XYZ]

Optional ifPresentOrElse() method

If a value is present, perform the given action with the value, otherwise, perform the given empty-based action.
Example:
package net.javaguides.corejava.java9;

import java.util.Optional;

/**
 * Demonstrates Java9 Optional Class improvements
 * @author Ramesh Fadatare
 *
 */
public class Java9OptionalClass {
    public static void main(String[] args) {
        Optional < Integer > optional = Optional.of(10);

        optional.ifPresentOrElse(x - > System.out.println("Value: " + x),
            () - > System.out.println("Not Present."));

        Optional < Integer > optional1 = Optional.empty();

        optional1.ifPresentOrElse(x - > System.out.println("Value: " + x),
            () - > System.out.println("Not Present."));
    }
}
Output:
Value: 10
Not Present.

Optional or() method

If a value is present, returns an Optional describing the value, otherwise returns an Optional produced by the supplying function.
Example:
package net.javaguides.corejava.java9;

import java.util.Optional;
import java.util.function.Supplier;

/**
 * Demonstrates Java9 Optional Class improvements
 * 
 * @author Ramesh Fadatare
 *
 */
public class Java9OptionalClass {
    public static void main(String[] args) {
        Optional < String > optional1 = Optional.of("Ramesh");

        Supplier < Optional < String >> supplierString = () - > Optional.of("Not Present");

        optional1 = optional1.or(supplierString);

        optional1.ifPresent(x - > System.out.println("Value: " + x));

        optional1 = Optional.empty();

        optional1 = optional1.or(supplierString);

        optional1.ifPresent(x - > System.out.println("Value: " + x));
    }
}
Output:
Value: Ramesh
Value: Not Present

Related Java 9 Posts


Comments