September 2019
Intermediate to advanced
816 pages
18h 47m
English
Sometimes, all we want is to consume a present Optional class. If Optional is not present then nothing needs to be done. An unskillful solution will rely on the isPresent()-get() pair, as follows:
// Avoidpublic void displayStatus() { Optional<String> status = ...; // this is prone to be empty if (status.isPresent()) { System.out.println(status.get()); }}
A better solution relies on ifPresent(), which takes Consumer as an argument. This is an alternative to the isPresent()-get() pair when we just need to consume the present value. The code can be rewritten as follows:
// Preferpublic void displayStatus() { Optional<String> status = ...; // this is prone to be empty status.ifPresent(System.out::println); ...