Java Magazine, Nov/Dec 2017
ORACLE COM JAVAMAGAZINE NOVEMBER DECEMBER 2017 100 fix this map In other words with a map operation the supplied function creates the data which might be null and leaves it to the map operation to wrap that in an Optional With flatMap the supplied function takes responsibility for providing an Optional directly And now you have the essence of this question Because the wrapped value in the question is in fact null the flatMap transformation is never executed The empty Optional that is returned from the flatMap is then used to invoke the map operation Therefore that map operation also skips executing its transformation for the same reason Finally the ifPresent method recognizes that the value is not present so it does not invoke the println behavior in the Consumer that is the argument to the ifPresent method As a result the code generates no output and the correct answer is option D For the reasons just outlined option E which suggests replacing the flatMap with a functionally equivalent map operation would not change the outcome Therefore option E is incorrect And given that the call to flatMap is a distraction its clear that both options A and B are incorrect So what about option C This looks as if it would see the empty state of the object on which its invoked and return a nonempty value It would but the problem here is that the return type of the orElseGet must be the content type of the Optional on which its invoked Therefore it would need to return a String to be compilable It doesnt so it wont compile and option C must be incorrect However if it did return a String instead of an Optional String youd still have a problem because then youd be attempting to call the map operation on a String and of course map is not defined as a String operation its an operation in the Optional class article Simon Roberts joined Sun Microsystems in time to teach Suns first Java classes in the UK He created the Sun Certified Java Programmer and Sun Certified Java Developer exams He wrote several Java certification guides and is currently a freelance educator who publishes recorded and live video training through Pearson InformIT available direct and through the OReilly Safari Books Online service He remains involved with Oracles Java certification projects
You must have JavaScript enabled to view digital editions.