Optional vs. null. What is the purpose of Optional in Java 8?

JavaJava 8

Java Problem Overview


In Java 8 you can return an Optional instead of a null. Java 8 documentation says that an Optional is "A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value."

In practice, why is this useful? Also, is there any case where using null would be preferred? What about performance?

Java Solutions


Solution 1 - Java

> In practice, why is this useful?

For example let's say you have this stream of integers and you're doing a filtering:

int x = IntStream.of(1, -3, 5)
                 .filter(x -> x % 2 == 0)
                 .findFirst(); //hypothetical assuming that there's no Optional in the API

You don't know in advance that the filter operation will remove all the values in the Stream.

Assume that there would be no Optional in the API. In this case, what should findFirst return?

The only possible way would be to throw an exception such as NoSuchElementException, which is IMO rather annoying, as I don't think it should stop the execution of your program (or you'd have to catch the exception, not very convenient either) and the filtering criteria could be more complex than that.

With the use of Optional, it's up to the caller to check whether the Optional is empty or not (i.e if your computation resulted in a value or not).

With reference type, you could also return null (but null could be a possible value in the case you filter only null values; so we're back to the exception case).

Concerning non-stream usages, in addition to prevent NPE, I think it also helps to design a more explicit API saying that the value may be present or not. For example consider this class:

class Car {
   RadioCar radioCar; //may be null or not 
   public Optional<RadioCar> getRadioCar() {
        return Optional.ofNullable(radioCar);
   }
}

Here you are clearly saying to the caller that the radio in the car is optional, it might be or not there.

Solution 2 - Java

When Java was first designed it was common practice to use a special value, usually called null to indicate special circumstances like I couldn't find what you were looking for. This practice was adopted by Java.

Since then it has been suggested that this practice should be considered an anti-pattern, especially for objects, because it means that you have to litter your code with null checks to achieve reliability and stability. It is also a pain when you want to put null into a collection for example.

The modern attitude is to use a special object that may or may not hold a value. This way you can safely create one and just not fill it with anything. Here you are seeing Java 8 encouraging this best-practice by providing an Optional object.

Solution 3 - Java

Optional helps you to handle variables as available or not available and avoid check null references.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJadiel de ArmasView Question on Stackoverflow
Solution 1 - JavaAlexis C.View Answer on Stackoverflow
Solution 2 - JavaOldCurmudgeonView Answer on Stackoverflow
Solution 3 - Javauser3728064View Answer on Stackoverflow