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 | public String getUsername(User user) { |
With Optional:
1 | public String getUsername(User user) { |
Create Optional object
There are 3 ways to create an Optional object:
Create an
Optionalthat has no value1
Optional<String> optional = Optional.empty();
Create an
Optionalthat the object must not be null1
Optional<String> optional1 = Optional.of("optional object");
Create an
Optional. The object could be null. In this case theOptionalhas no value1
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 | Optional<User> optionalUser = Optional.ofNullable(user); |
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")) |