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:

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:
if (title != null) {
  • 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.
movie.setTitle(Objects.nonNull(title) ? title : movie.getTitle());
  • 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.
public static <V> void setIfNotNull(V value, Consumer<V> setter) {
    if (Objects.nonNull(value)) {

and you call it like this:

setIfNotNull(title, movie::setTitle);

That last one only makes sense if you are using it a lot.

Download the complete code from this post here