6

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.

user3138984
  • 126
  • 1
  • 1
  • 6
  • 1
    Well, in order to check for null you have to check for null :-) – Christopher Schneider May 04 '16 at 13:02
  • I searched similar questions before posting, and I've not found this. Maybe is different. My problem is to not overwrite existing data in a pojo with a null value. Because my not long experience with java (I started to use it 1 year and some months ago), I hoped for the existence of a better way to do this. – user3138984 May 04 '16 at 13:25

2 Answers2

17

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);
Sergii Bishyr
  • 8,331
  • 6
  • 40
  • 69
0

Use guava:

String someString = "value";
Optional.fromNullable(someString).or("defaultValue");
g-t
  • 1,455
  • 12
  • 17