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?
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;
                ...
            }
        });
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With