How to correctly use Java 8 option to conditionally return values or throw exceptions?

I want to implement code like the following to verify the input in my @ restcontroller so that I can avoid explicit null checking, but I'm stuck

public @ResponseBody Response getCityDetails(@RequestParam("city") final String city) {
    Optional.of(city).ifPresent(name -> {
        // return value
        return service.getDetails(name);
    }).orElseThrow(//some Exception);
}

Solution

Try this

Optional.ofNullable(city)
        .map(name ->service.getDetails(name))
        .orElseThrow(//some Exception);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>