DEV Community

Juan Sedano
Juan Sedano

Posted on • Originally published at jsedano.dev on

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:
if (title != null) {
    movie.setTitle(title);
}
Enter fullscreen mode Exit fullscreen mode
  • 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());
Enter fullscreen mode Exit fullscreen mode
  • Very elegant way, although you are creating a new Object with the ofNullable call, but I guess it’s ok.
Optional.ofNullable(title).ifPresent(movie::setTitle);
Enter fullscreen mode Exit fullscreen mode
  • 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)) {
        setter.accept(value);
    }
}
Enter fullscreen mode Exit fullscreen mode

and you call it like this:

setIfNotNull(title, movie::setTitle);
Enter fullscreen mode Exit fullscreen mode

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

Download the complete code from this post here SetIfNotNull.java.

Top comments (0)