September 2019
Intermediate to advanced
816 pages
18h 47m
English
So, if we have decided to call Optional.get() to fetch the value wrapped in Optional, then we shouldn't do it as follows:
Optional<Book> book = ...; // this is prone to be empty// Avoid// if "book" is empty then the following code will// throw a java.util.NoSuchElementExceptionBook theBook = book.get();
In other words, before fetching the value via Optional.get(), we need to prove that the value is present. A solution consists of calling isPresent() before calling get(). This way, we add a check that allows us to handle the missing value case:
Optional<Book> book = ...; // this is prone to be empty// Preferif (book.isPresent()) { Book theBook = book.get(); ... // do something with "theBook"} else { ... ...