/ Java  

Java 8 Optional

Java 8 introduced Optional class to avoid NullPointerException. Basically Optional class is a container to represent if an object exist or not. Use Optional make null value handling more elegant. See the example:

1
2
3
4
5
6
7
8
public String getUsername(User user) {
if(user == null)
{
return "Unkown";
}

return user.getUsername();
}

With Optional:

1
2
3
public String getUsername(User user) {
return Optional.ofNullable(user).map(u -> u.getUsername()).orElse("Unkown");
}

Create Optional object

There are 3 ways to create an Optional object:

  1. Create an Optional that has no value

    1
    Optional<String> optional = Optional.empty();
  2. Create an Optional that the object must not be null

    1
    Optional<String> optional1 = Optional.of("optional object");
  3. Create an Optional. The object could be null. In this case the Optional has no value

    1
    Optional<String> optional2 = Optional.ofNullable(null);

get() Method

It is used to return the value of the wrapper object. But if the wrapper object value is null, a NoSuchElementException will be thrown.

isPresent() Method

Used to determined the if the object is not null. Using it is not a good behavior as the logic would be excatly the same if we do a null check. And we are introducing an extra step to wrap the object with Optional

ifPresent() Method

The ifPresent() accept a Consumer Interface as parameter. If the object is not null then the Consumer Interface will be called to perform a specific action.

1
2
3
4
Optional<User> optionalUser = Optional.ofNullable(user);

// if user exist then print the username
optionalUser.ifPresent(user -> System.out.println(user.getUsername()));

filter() Method

The filter()method accepts a Predicate interface, which is used to filter the Optional object. If the condition of Predicate is met, the Optional object itself is returned. Otherwise, an empty Optional object is returned.

1
Optional.ofNullable(item).filter( i -> i.getPrice() > 100).ifPresent(i ->  System.out.println("The item cost over $100"));

map() Method

The map() method takes a Function object. It uses the Function to the Optional and wrap it into a new Optional object (the type of the wrapper object may change).

1
Optional.ofNullable(user).map(u -> u.getUsername());

orElse() Method

If the Optional object is not null, then return it’s value. Otherwise return the default value specified as the function parameter.

1
Optional.ofNullable(user).map(u -> u.getUsername()).orElse("Unkown");

orElseGet() Method

Similar to orElse(), except that the parameter of the orElseGet() is a Supplier object. The return value of the get() of the Supplier object is used as the default value.

1
Optional.ofNullable(user).map(u -> u.getUsername()).orElseGet(() -> "Unkown");

orElseThrow() Method

Similar to orElseGet(). The parameters are all Supplier objects, except that the Supplier object of orElseThrow() must return a Throwable exception. The orElseThrow() method is useful for scenarios where a specific exception needs to be thrown when the wrapped object value is null.

1
Optional.ofNullable(user).map(u -> u.getUsername()).orElseThrow(() -> new RuntimeException("Unkown"))