Is there a way to combine Java8 Optional returning a value with printing a message on null?

不问归期 提交于 2020-01-03 06:42:09

问题


I'm starting with this code:

String startingValue = getMyValue();
String finishingValue = "";
if (startingValue != null) {
    finishingValue = startingValue;
} else {
    System.out.println("Value was null");
}

I want to transform it using Java 8 options to something like this:

Optional<String> startingOptional = getMyOptional();
String finishingValue =
        startingOptional
                .map(value -> value)
                .orElse(System.out.println("value not found"));

My question is: Is there a way to combine Java8 Optional returning a value with printing a message on null?


回答1:


Use orElseGet:

Optional<String> startingOptional = getMyOptional();
String finishingValue = startingOptional.orElseGet(() -> {
    System.out.println("value not found");
    return "";
});

Using .map(value -> value) is useless: transforming a value into itself doesn't change anything.




回答2:


If you are using Java 9 or later and you don't want to use default stub for empty value but instead handle empty and non-empty cases separately, you can also use Optional#ifPresentOrElse(Consumer, Runnable) method whose second argument is the handler for empty value. For your case it would look like:

Optional<String> startingOptional = getMyOptional();
finishingValue =
        startingOptional
                .map(value -> value)
                .ifPresentOrElse(
                        value -> {/* do something with your value */},
                        () -> System.out.println("value not found")
                );

or, ommiting the local variable:

getMyOptional()
        .map(value -> value)
        .ifPresentOrElse(
                value -> {/* do something with your value */},
                () -> System.out.println("value not found")
        );


来源:https://stackoverflow.com/questions/59517743/is-there-a-way-to-combine-java8-optional-returning-a-value-with-printing-a-messa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!