Java Magazine, September/October 2017
ORACLE COM JAVAMAGAZINE SEPTEMBER OCTOBER 2017 34 java 9 In this example you combined two Optional methods to achieve your goal You used a filter on the isPresent method in order to remove empty Optionals Then you unboxed the Optional objects that you knew had a value with the get method call You can make this code less clunky in Java 9 A method on Optional has been added that returns a stream called funnily enough stream It will give you a Stream with an element in it if the Optional has one or it will be empty otherwise Lets see how the code looks with this approach List Setting settings SETTING_ NAMES stream map this lookupSettingByName flatMap Optional stream collect toList This new addition also means that it is simpler to integrate Optional with APIs expecting to work with streams ifPresentOrElse The new ifPresentOrElse method encodes a common pattern for performing one action if an Optional value is present or performing a diferent action if its absent To understand this feature lets take an example of someone trying to check in for an airline flight to see how you would write this code first using null checks and then with the Optional type The user provides a booking reference with which you look up their booking If you have a booking associated with that reference you display the check in page otherwise you display a page explaining that the booking record is missing If the lookupBooking method were to return null in order to indicate that the booking is missing your code might look like the following Booking booking lookupBooking bookingRef if booking null displayCheckIn booking else
You must have JavaScript enabled to view digital editions.