Java Optional the missing ifNotPresent

By | June 12, 2016

Ever since Java 8 developers were given a great way to wrap null value checks, the Optional class. This class enables you to prevent nasty NullPointerException in your code in a clean way. Just look at the cleaner code below

// Old code
Ticker myTicket = ticketRepository.get("someId");
if (ticket == null) {
   throw new NotFoundException();

return convertTicket(ticket);

// New code
return Optional.ofNullable(ticketRepository.get("someId"))
     .map(t -> this::convertTicket)
     .orElseThrow(() -> new NotFoundException());

As you can see the new code is fewer lines and easier to read. The Optional provides a lot of functionality to confirm if something is present within, but for some reason is lacking functionality to handle the cases when nothing is contained within the Optional. For example to handle an edge case where you are not interested in the value within but only in if one is not present you will have to write:

// Check if entity already exists
if (Optional.ofNullable(ticketRepository.get("someId")).isPresent()) {
   throw new AlreadyExistsException();

Would it not be preferable to write smaller and easier to read code here as well. For example something like:

    .ifPresent(() -> new AlreadyExistsException());

It is a pity that so many functionalities are still missing in the Optional class. For that reason a new version of Optional was written in the JongSoft Java Language libraries. The library is not yet completed but does already contain an extended version of the Java SE Optional class.

Leave a Reply