Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorter way to do nullchecking

Tags:

java

Probably asked before, but could not find it.

I am writing a lot of statements in the form:

if (bar.getFoo() != null) {
    this.foo = bar.getFoo();
}

I thought of the ternary operator, but that doesn't make it much better in my opinion:

this.foo = bar.getFoo() != null ? bar.getFoo() : this.foo;

My main problem is that I have to write bar.getFoo() twice in both situations. Of course I can write a helper method that solves this, but I was wondering if there were more elegant solutions.

Different from: Avoiding != null statements because that question does not deal with assigning to a value the value that is null checked on.

like image 883
Martijn Burger Avatar asked Dec 03 '25 09:12

Martijn Burger


2 Answers

This avoids the if statement and calls getFoo() once. But you have to type this.foo twice:

this.foo = Objects.requireNonNullElse​(bar.getFoo(), this.foo);

requireNonNullElse​ docs

like image 187
Manos Nikolaidis Avatar answered Dec 06 '25 15:12

Manos Nikolaidis


As written in Optional javadoc:

A container object which may or may not contain a non-null value.

Having said that this is the most "java-8" way of dealing with null checks. This was one of the original intentions of Java Optional introduction. Having getFoo returning an Optional you can just use the ifPresent function on the Optional and you are good to go.

like image 31
Varvarigos Emmanouil Avatar answered Dec 06 '25 13:12

Varvarigos Emmanouil