Rasool Ghafari Rasool Ghafari - 1 year ago 78
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
instead of using
, or if there is another thing that can I use it?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download