Rasool Ghafari Rasool Ghafari - 18 days ago 4
Java Question

How to check if null and have specific value with Optional in java?

Assume that I have this code in my project:

public List<T> getAll(Integer parameter) {
if(parameter != null && parameter > -1) {
// do something here
}
}


My question is: how can I do the checking with
Optional
instead of using
if
, or if there is another thing that can I use it?

Answer

Use Optional<Integer>

public List<T> getAll(Optional<Integer> paramter) {
    if(parameter.isPresent() && parameter.get() > -1) {
        // do something here
    }
}

The Optional<> is just an implementation of Optional pattern. The useful methods is also Optional<T>#orElse(T default) which sets the value to default in case there was a null,

If you already have Guave in your project, I would recommend using Guava Optional.

If you already got interested but still can't answer your doubts, please ask for clarification in comments. I'll respond asap.

Comments