top of page
Search

Java 9 Optional Class Improvements

  • schick09
  • Aug 27, 2024
  • 2 min read

Java 9 introduced several improvements to the Optional class which we will describe below with examples.


Factory Method Improvements


Java 9 introduced the factory method Optional.ofNullable(value), which allows the 'value' to be null. Before this, Optional.of(value) would throw a NullPointerException if the 'value' was null. This saves us from having to do any preliminary null checks prior to using the value.



    public static void factoryMethodImprovements(){
        /**
         * In this case, the value can't be null or you'll get a NullPointerException
         */
        Optional<String> thisworks = Optional.of("I am a non-null value!");
        /**
         * This would throw an NPE if it wasn't commented out
         */
        //Optional<String> thisthrowsnpe = Optional.of(null);
        /**
         * Returns an Optional with the value if non-null
         * Returns an empty Optional if value is null
         */
        Optional<String> emptyOptional = Optional.ofNullable(null);
    }



ifPresentOrElse


Java 9 introduced the ifPresentOrElse(value) method to the Optional class. This lets us define the action to take if the 'value' is present and also the action to take if the 'value' is empty.


    public static void ifpresentorelse (){
        Optional<String> thisworks = Optional.of("I am a non-null value!");
        thisworks.ifPresentOrElse(
                value -> System.out.println("Value is present: " + value),
                () -> System.out.println("Value is absent")
        );
        /**
         * Prints out:  Value is present: I am a non-null value!
         */
        Optional<String> emptyOptional = Optional.ofNullable(null);
        emptyOptional.ifPresentOrElse(
                value -> System.out.println("Value is present: " + value),
                () -> System.out.println("Value is absent")
        );
        /**
         * Prints out:  Value is absent
         */
    }


or() and stream() methods


Java 9 introduced the or() and stream() methods. The or() method lets you specify a default Optional value if the current value is empty. The stream() method transforms an Optional containing a value into a Stream. From there you can use all of the Stream API processing options available.


    public static void orandstream(){
        /**
         * or() method example
         */
        Optional<String> emptyOptional = Optional.ofNullable(null);
        Optional<String> defaultOptional = emptyOptional.or(() -> Optional.of("Here's a default value for you"));
        System.out.println("Optional Default value: " + defaultOptional.get());
        /**
         *  stream() method example
         */
        Optional<String> thisworks = Optional.of("Hey, I've got a value!");
        Stream<String> streamFromOptional = thisworks.stream();
        streamFromOptional.forEach(value -> System.out.println("Stream Value: " + value));
    }


Using ifPresentOrElse() and or() to Chain Default Optional Values


You can use ifPresentOrElse() and or() to chain default Optional values. For example, if one Optional default value happens to be null, you can return a 'second choice' Optional default value. The example below will clarify.


 public static void chainingexample(){
        // ifPresentOrElse() and or() methods chaining
        Optional<String> emptyOptional = Optional.ofNullable(null);
        Optional<String> emptyOptional2 = Optional.ofNullable(null);
        Optional<String> chainedOptional = emptyOptional
                .or(() -> emptyOptional2)
                .or(() -> Optional.of("Use This Default Value"));
        System.out.println("Chained Optional value: " + chainedOptional.get());
    }
    /**
     * In this example, 3 Optional<String> values are converted to a Stream<Optional</String>>
     * and then flattened into a Stream<String>.
     */
    public static void optionalstreamconversion(){
        Optional<String> emptyOptional = Optional.ofNullable(null);
        Optional<String> thisworks = Optional.of("Hey, I've got a value!");
        Optional<String> defaultOptional = Optional.of("default value");
        Stream<Optional<String>> optionalStream = Stream.of(thisworks, emptyOptional, defaultOptional);
        Stream<String> flattenedStream = optionalStream.flatMap(Optional::stream);
        flattenedStream.forEach(value -> System.out.println("Flattened Stream Value: " + value));
        /**
         * Prints out:
         * Flattened Stream Value: Hey, I've got a value!
         * Flattened Stream Value: default value
         */
    }
}

Here's a link to our GitHub location to access an example of using the Optional class improvements shown above: https://github.com/daveschickconsulting/java_9_examples/tree/main/src/letsimproveoptionals




 
 
 

Comments


Dave Schick Consulting

©2023 by Dave Schick Consulting. Proudly created with Wix.com

bottom of page