Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare an Integer using least code?

Tags:

java

There is an Integer property called foo in a model. Now I need to know whether it equals 1 or 2. Usually I use:

if (null != model) {
    Integer foo = model.getFoo();
    if (foo != null) {
        if (foo == 1) {
            // do something...
        }
        if (foo == 2) {
            // do something...
        }
    }
}

Is there any handier code to avoid the NullPointerException?

like image 498
code-life balance Avatar asked Dec 14 '22 13:12

code-life balance


1 Answers

You can use Optional:

Optional.ofNullable(model)
        .map(Model::getFoo)
        .ifPresent(foo -> {
            switch (foo) { // or if-else-if, the important thing is you skip the null check
                case 1: 
                    ...
                    break;
                case 2:
                    ...
                    break;
                ...
            }

        });
like image 158
Eran Avatar answered Jan 26 '23 01:01

Eran