Optional in Java 8

Optional was introduced in Java 8 to handle null references and NullPointerException.

Null references to Object has many issues few of which I have listed below:

  • Its a source of error, Null reference lead us to NullPointerException
  • To handle null reference, we need to add null checks which bloats our code
  • Its a wrong way to handle the absence of value in a statically typed language
  • In a nutshell, there are many issues when Objects has null reference , therefore to eliminate them Optional Class is introduced in Java8. Lets see how it solves the problem

Previous to Java 8 code was like below:

This code has lot of issues like if emp is null or Car returned by Employee is null or Insurance returned by Car is null than it will throw NullPointerException

To fix above code prior to java 8, we were suppose to handle it with null checks like below.

Using Optional with Java 8:we can declare instance variable Optional Type if variable can be null, like below

We need to see now how to Create Optional:

Creating Empty Optional:Optional Class has static factory method empty to create empty optional

Optional<Car> car =  Optional.empty();

Creating Optional from a non-null value:If we have any not null object and we want to create Optional Type object from it we can do so using static factory method Of of Optional Class

Optional<Car> optionalCar =  Optional.of(car);

Creating Optional From Nullable value: If we have any object which can be null, we can use static factory method OfNullable to create Optional Object,this will return empty Optional if object is null

Optional<Car> nullableOptionalCar =  Optional.ofNullable(car);

If we need to re-write previous method getCarInsuranceNameForEmployee with Java8 ,we can write like below

Here I have used flatMap as using map would return Optional of type Optional like below, so removing flatMap will remove nested Optional Types

Combining 2 optionals:As mentioned earlier like we can use optional in method argument and for example if we want to call a method by giving 2 argument we can turn them to optional type and check if value is present then proceed otherwise we can return empty optional like shown below

We can also do it in 1 linear like shown below without calling the get method on Optional and checking if Optional is present like shown below

Here if employee is empty lambda expression passed inside flatMap will not be executed and if car is empty and employee is present then lambda expression inside map method of car will not execute, only if both car and employee are present then only findInsurance method will be called

Using Filters In Optional: Optional has introduced filter method

  /**
     * If a value is present, and the value matches the given predicate,
     * return an {@code Optional} describing the value, otherwise return an
     * empty {@code Optional}.
     *
     * @param predicate a predicate to apply to the value, if present
     * @return an {@code Optional} describing the value of this {@code Optional}
     * if a value is present and the value matches the given predicate,
     * otherwise an empty {@code Optional}
     * @throws NullPointerException if the predicate is null
     */
public Optional<T> filter(Predicate<? super T> predicate) {
        Objects.requireNonNull(predicate);
        if (!isPresent())
            return this;
        else
            return predicate.test(value) ? this : empty();
    }

this filter method takes Predicate and returns a boolean based upon which Value is filtered Example:

Here we are passing Optional Type Insurance Object and checking if Insurance type equals to specific value then only printing it.

The above IfPresent() method is used to check if value is present and filtering it based upon the predicate which returns true and false

OrElse Method Of Optional: OrElse method is used to return the value if Present otherwise it returns the value passed in the argument

 public T orElse(T other) {
        return value != null ? value : other;
    }
This orElse will return “SampleValue” if optionalName dont have value present else value present in OptionalName is returned

You may also like...

1 Response

  1. Hello, everything is going sound here and ofcourse every one
    is sharing information, that’s actually excellent, keep up writing. https://completereliefcbd.org/

Leave a Reply

Your email address will not be published. Required fields are marked *