Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set property only if is not null [duplicate]

Tags:

java

I have some data in input that I'll have to use to set all properties of a POJO. The POJO might be partially set. My problem is to set the property only if related input data is not null. I know I can do this in two ways:

if (input != null) {
    obj.setData(input);
}

or

obj.setData(input != null ? input : obj.getData());

I'm looking for a solution less ugly and better for objects with a big number of properties to set.

like image 392
user3138984 Avatar asked Dec 07 '22 22:12

user3138984


1 Answers

You can also use java8 Optional

obj.setData(Optional.ofNullable(input).orElse(obj.getData()));

Or even use a more elegant way:

Optional.ofNullable(input).ifPresent(obj::setData);
like image 197
Sergii Bishyr Avatar answered Dec 10 '22 11:12

Sergii Bishyr