Set if not null Java
Simple ways to check if a value is null before setting it to some object in Java.
You can find the complete code for this here: SetIfNotNull.java
Consider you have a class Movie
with an attribute title
along with the correspondent setter, and you want to set some new value for the title
but only if such value is not null.
- A very traditional way:
- Using ternary operator, in the case
title
is null you would be placing the same value on the Object which may look a little ugly.
- Very elegant way, although you are creating a new Object with the
ofNullable
call, but I guess it’s ok.
- Creating a little helper method which receives the value and a
Consumer
that sets the value in the object.
and you call it like this:
That last one only makes sense if you are using it a lot.
Download the complete code from this post here SetIfNotNull.java.