Java Magazine, September/October 2017
ORACLE COM JAVAMAGAZINE SEPTEMBER OCTOBER 2017 36 java 9 lookupBooking bookingReference ifPresentOrElse this displayCheckIn this displayMissingBookingPage or Another method that has been added to Optional in Java 9 is the succinctly named or method It takes as an argument a function that creates an Optional If the object on which it is invoked has a value present the value is returned otherwise the function is called and its result is returned This is particularly useful when you have several methods that all return Optionals and you want to return the first one that is present Suppose you want to look up information about clients using a company identifier such as the company number First you want to check your existing client datastore to see whether the company is in there If it isnt you want to create a new client by looking up information about the company in an alternative service Perhaps the provided ID is a typo from a user and the ID cant be looked up at all If you suppose that your methods just return null in order to indicate that the value is missing you might write the following code Client client findClient companyId if client null client lookupCompanyDetails companyId client could still be null If you refactor findClient to return an Optional you can use the orElseGet method from Java 8 which will call your lookupCompanyDetails method only if the Optional is absent for example Client client findClient companyId
You must have JavaScript enabled to view digital editions.