Wednesday, August 22, 2018

Java9 - Optional Class Improvements with examples | Java9 Features

We already discussed Optional class introduced in Java8.

java9 Optional Class Improvements

Java9 features -  Optional Class Improvements with examples
In this article post, We are going to discuss enhanced features added to the java9 Optional class. With java9, Added few more features to existing Optional class in java8. java.util.Optional has below methods.
  1. stream()
  2. ifPresentOrElse()
  3. or()

These methods are added to primitive Optional classes: OptionalInt, OptionalLong, OptionalDouble.

Java9 Optional.Stream() method example

This method allows converting Optional Object to Stream Object.
Java has good API for manipulation of collection data structures using functional programming. 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 empty Stream. This is very useful when you are doing iterations with Optional values.
Let us see Convert list of strings to upper cause example in Java 8 and Java 9.
For example, Create a List of strings as follows
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 - How to convert String List to Uppercase List
Java8, we have isPresent and get method
During the stream of list iteration, we are checking isPresent() method for not null/empty and retrieve the element using get() method and map to list.
List<String> stringList = listOptionalStrings.stream().filter(Optional::isPresent).map(Optional::get)
    .map(String::toUpperCase).collect(Collectors.toList());
  stringList.forEach((value) -> {
   System.out.println(value);
  });
Java8 - How to convert String List to Uppercase List
Using optional stream, We will combine isPresent() and get() method with Stream() method
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 and here is
ONE
TWO
THREE
FOUR

Java9 Optional.ifPresentOrElse() method example

Optional.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
Optional<String> stringOptional = Optional.ofNullable("present");
  if (stringOptional.isPresent()) {
   System.out.println(stringOptional.get());
  } else {
   System.out.println("Default");
  }
isPresent() method used to check value is present or not. and have to add conditional logic to add else logic.
ifPresent() method can also be used to execute a consumer when the value is presented. There is no else support here.
with java9, ifPresentOrElse() method is used to have if and else logic
Optional<String> stringOptional = Optional.ofNullable("present");
  stringOptional.ifPresentOrElse(value -> System.out.println(value), () -> System.out.println("Default"));

Output is
present

Java 9 Optional.or() method

Or() method checks and if value is present, return option contains value.
Else, retun Optional applies to Supplier funciton
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.

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 is
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 Optional object.
or() method provides the implementation for returning Optional object and functionality is same as like orElse(), orElseGet() methods.
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 is
Optional[defaultvalue]
Optional[one]

Related article


EmoticonEmoticon