Java 9: Enhance your Java 8 code with Java 9 Optional API enhancement

Reading Time: 3 minutes

I am using Java 8 for quite a long time now. I started with Scala and then later worked on Java 8. I noticed that some of the features are very strong in Scala which is not in Java 8. I would like to discuss one of the features here which is Optional. Java introduced Optional in Java 8 but with some limited power but gradually Java is making them better in new versions.

Recently, I went through Java 9 features and noticed that there are some improvements in Optional API. When I used Java8 Optional, I missed some of the features from Optional which Java 9 has included now.

So here, we will discuss how we can enhance the java 8 code with the help of Java 9 API enhancement.

Java 9 has added 3 new features in Optional API which are as follows:

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

We will discuss all 3 methods one by one.

ifPresentOrElse():

When we have an Optional instance, then we want to perform the different actions based on whether Optional is having value or not.

ifPresentOrElse() method does the same. It gives us the features that we can perform different actions in different cases. We can pass a Consumer that will be invoked if the Optional is defined, and Runnable that will be executed if the Optional is empty.

Bur before going into the examples, we will see how we used to handle the above scenario in Java 8:

Java 8:

Suppose, we have an Optional String variable

Optional<String> name = Optional.of("Rishi");

We want to perform 2 different actions based on its value existence.

Case-1:

if (name.isPresent()) {
    System.out.println("Hello " + name.get());
} else {
    System.out.println("Hello Guest");
}

Case-2:

name.map(x -> {
    System.out.println("Hello " + x);
    return x;
}).orElseGet(() -> {
    System.out.println("Hello Guest");
    return "";
});

We have ifPresent() method as well in Java 8 but that does not give us the flexibility to write the else logic.

name.ifPresent(x -> System.out.println("Hello " + x));

Java 9:

name.ifPresentOrElse(x -> System.out.println("Hello " + x),
        () -> System.out.println("Hello Guest"));

See, how well we can write the above scenario in Java 9 with less code.

stream():

The new stream() method allows us to convert an Optional to a Stream.

If the Optional contains a value, it will return a Stream containing only that value, otherwise, it will return an empty Stream.

Optional<String> nameOptional = Optional.of("Rishi");

Stream<String> nameOptionalStream = nameOptional.stream();

nameOptionalStream.forEach(System.out::println);

Output will be :

Rishi

Now let see the use case, where we can use this feature.

Suppose we have a list of Optional of String of name

List<Optional<String>> listOption = Arrays.asList(
        Optional.of("Sachin"), Optional.of("Sehwag"),
        Optional.empty(), Optional.of("Dravid"));

And we need to get the list of names, so let see how e can do that in Java 8 and Java 9.

Java 8 :

List<String> list = listOption.stream()
        .filter(Optional::isPresent)
        .map(Optional::get)
        .collect(Collectors.toList());

Java 9:

List<String> list = listOption.stream()
        .flatMap(Optional::stream)
        .collect(Collectors.toList());

You can see, we have called stream() method on Optional which gives again a stream, so we get Stream<Stream> and to flat this, we have used flatMap.

In Java 9 code, there is no need to check whether Optional is having some value or not. stream() method will handle that automatically.

So this is a very helpful feature and I liked it most as I use this use case most often in my code. 🙂

or():

Optional is already having 2 methods: orElse() and orElseGet() which returns a default value if Optional is empty. This default value is the unwrapped value instead of an Optional.

Suppose we have an Optional value:

Optional<String> name = Optional.empty();

orElse():

name.orElse("Guest");

orElseGet():

name.orElseGet(() -> {
    System.out.println("Returning the default value");
    return "Guest";
});

But sometimes we get the scenario, where we want to return the Optional value as the default value instead of the unwrapped values, so here or() will be very useful.

Let’s see, how we will handle this use case in Java 8.

Java 8:

Optional<String> value = name.isPresent() ? name : Optional.of("Guest");

Java 9 :

Optional<String> value = name.or(() -> Optional.of("Guest"));

That’s it. We have discussed all 3 enhancements in Java 9 Optional API. I think, they are very useful and will help us to write better code.

I hope this blog will give a better understanding of new enhancement and will help you to understand the use cases as well.

blog-footer

Written by 

Rishi is a tech enthusiast with having around 10 years of experience who loves to solve complex problems with pure quality. He is a functional programmer and loves to learn new trending technologies. His leadership skill is well prooven and has delivered multiple distributed applications with high scalability and availability by keeping the Reactive principles in mind. He is well versed with Scala, Akka, Akka HTTP, Akka Streams, Java8, Reactive principles, Microservice architecture, Async programming, functional programming, distributed systems, AWS, docker.

1 thought on “Java 9: Enhance your Java 8 code with Java 9 Optional API enhancement4 min read

Comments are closed.