Java Magazine, September/October 2017
ORACLE COM JAVAMAGAZINE SEPTEMBER OCTOBER 2017 37 java 9 orElseGet lookupCompanyDetails companyId However this still does not model your use case correctly Because the companyId might not correspond to an actual company identifier the lookupCompanyDetails method can still fail If you take the route of modeling failure using the Optional type you should also make that method return an Optional This is where the new or method comes into play You get an Optional Client back If you could look up the client in your database then that client would be the value that is present If it is a valid new company that will be returned If it contains a typo the Optional will be empty Heres the code Optional Client client findClient companyId or lookupCompanyDetails companyId So far this article has discussed how Optional in Java 8 has been improved in Java 9 with a series of targeted methods that satisfy missing use cases The primitive specialized Optional classes such as OptionalInt arent getting all the same love stream and ifPresentOrElse were added to them but or was not CompletableFuture Java 8 introduced CompletableFuture T as an enhancement to Future T It is a class that lets you express the flow of information from different tasks using a callback driven style In the rest of this article you will see the improvements that Java 9 brings to these Futures Well first introduce a typical problem Well then show several ways to address the problem in Java 8 and then well demonstrate in the final section how Java 9 provides better alternatives Combining two services Suppose that youd like to combine the result of two services over the network a best price finder for a flight route and an exchange service that converts USD
You must have JavaScript enabled to view digital editions.