Aleksandar Aleksandar - 1 year ago 102
Java Question

Java 8 avoiding null pointer checks using Optional

Is it possible to write something like this and to avoid checking if elements are not null and collections not empty:


I found something like this

Basically, what I want to achieve is to avoid if statement with multiple checking weather object is null or collection is empty in the hierarchy. I read in the post from my above that this is possible with Optional "Null checks are automatically handled under the hood."

If there is some solution already, sorry for making duplicate and please refer me to it.

Answer Source

If you want to chain Optional, you can use its map(Function<? super T,? extends U> mapper) method to call the mapper function only if it is not null and use flatMap(Stream::findFirst) to get the first element of your Collection as next:

Optional<List<ResultParameterClass>> parameters = Optional.ofNullable(response)

Is it possible to return the list if present in Optional, or if not present then return something like new ArrayList<ResultParameterClass>()?

Yes it is, you simply need to use orElseGet(Supplier<? extends T> other) or orElse(T other) to provide a default value, the result won't be an Optional anymore but a List<ResultParameterClass>.

So the code would then be:

List<ResultParameterClass> parameters = Optional.ofNullable(response)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download