I want to implement something like below code to validate inputs in my @RestController
so that I can avoid explicit null checks, However I am stuck.
public @ResponseBody Response getCityDetails(@RequestParam("city") final String city) {
Optional.of(city).ifPresent(name -> {
// return value
return service.getDetails(name);
}).orElseThrow(//some Exception);
}
Simply put, if the value is present, then isPresent() would return true, and calling get() will return this value. Otherwise, it throws NoSuchElementException. There's also a method orElseThrow(Supplier<? extends X> exceptionSupplier) that allows us to provide a custom Exception instance.
static <T> Optional<T> ofNullable(T value) Returns an Optional describing the specified value, if non-null, otherwise returns an empty Optional.
The method orElse is one more interesting method of Optional. It returns the contained value if it is not null. Otherwise it returns the given default value.
Try this
Optional.ofNullable(city)
.map(name ->service.getDetails(name))
.orElseThrow(//some Exception);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With