How to correctly use Java 8 option to conditionally return values or throw exceptions?
•
Java
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
二维码