Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Java 8 Optional properly that can conditionally return a value or throw exception?

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);
}
like image 298
shankulk Avatar asked Dec 03 '18 07:12

shankulk


People also ask

How do you throw an exception in Optional?

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.

Which of the following methods of Optional class can be used to throw an exception of your choice if an object is null?

static <T> Optional<T> ofNullable(T value) Returns an Optional describing the specified value, if non-null, otherwise returns an empty Optional.

Which is the method of Optional class in functional programming in Java 8 that is used for avoiding Nullpointerexception when we chain functions?

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.


1 Answers

Try this

Optional.ofNullable(city)
        .map(name ->service.getDetails(name))
        .orElseThrow(//some Exception);
like image 68
Hadi J Avatar answered Nov 14 '22 22:11

Hadi J