Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Juan Sedano
Juan Sedano

Posted on • Originally published atjsedano.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 classMovie with an attributetitle along with the correspondent setter, and you want to set some new value for thetitle but only if such value is not null.

  • A very traditional way:
if (title != null) {    movie.setTitle(title);}
Enter fullscreen modeExit fullscreen mode
  • Using ternary operator, in the casetitle 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 modeExit fullscreen mode
  • Very elegant way, although you are creating a new Object with theofNullable call, but I guess it’s ok.
Optional.ofNullable(title).ifPresent(movie::setTitle);
Enter fullscreen modeExit fullscreen mode
  • Creating a little helper method which receives the value and aConsumer 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 modeExit fullscreen mode

and you call it like this:

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

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

Download the complete code from this post hereSetIfNotNull.java.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Hi! I just want to learn and share : )
  • Location
    Guadalajara, México
  • Work
    Tech lead at Clip
  • Joined

More fromJuan Sedano

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp