Avoid isPresent() and get() in control logic
问题 Is there a prettier way of doing the following in Java 8, avoiding isPresent and get ? void doStuff(String someValue, Optional<Boolean> doIt) { if (doIt.isPresent()) { if (doIt.get()) { trueMethod(someValue); } else { falseMethod(someValue); } } } I tried using map , without success. But I probably didn't try hard enough? 回答1: You can use ifPresent instead of isPresent and get : void doStuff(String someValue, Optional<Boolean> doIt) { doIt.ifPresent (b -> { if (b) trueMethod(someValue); else