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.
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
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.
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