Java Magazine, Nov/Dec 2017
ORACLE COM JAVAMAGAZINE NOVEMBER DECEMBER 2017 99 fix this if s null s s toLowerCase Instead an Optional allows you to perform operations on the data that it wraps creating a new Optional as a result but if the original Optional wrapped a null the transformation is simply skipped thereby avoiding the clutter of checking for null in the caller So the above code would be replaced with this Optional String os operationThatReturnsOptionalString map String toLowerCase In this the operationThatMightReturnNull has been rewritten to return an Optional directly It didnt have to be you could wrap it using Optional ofNullable operationThatMightReturnNull but its cleaner this way and reflects a more complete adoption of the Optional into the softwares design The important thing is that if the initial function call returns an empty Optional that is an Optional that wraps a nonexistent object the operation specified in the map call is never called and the result of the entire chain is an empty Optional Side note Although as a rule the map call and similar operations return a new Optional object the classs implementation appears to be smart about representing emptiness it generally reuses the same underlying instance for every empty Optional Thats not guaranteed behavior the API documentation warns against that assumption but its a smart way to save memory and has no other consequences unless you do some strange and improbable things with operations without knowing about this singleton design The operation flatMap is essentially the same as a map except that its used in situations where the function that is provided as an argument returns the result of the flatMap directly that result is an Optional Contrast this with the map operation where the supplied function returns data that will be wrapped by the map operation into an Optional that will be returned by
You must have JavaScript enabled to view digital editions.