Home > Software design >  Java 8 Replace two null check with Optional
Java 8 Replace two null check with Optional

Time:12-13

Below is my code which is working as expected. But I need to replace it with Optional.ofNullable

if (getFirstData != null && getSecondData !=null {
 ... doing my work here
} else {
  ... doing my else work here
}

How can I use Optionals.ofNullable(..) to replace two AND null checks?

CodePudding user response:

It may be a bit overkill, but if there's need to check multiple values for nulls, it may be done like this using Optional:

static boolean allNonNullsOptional(Object ... items) {
    return Stream.of(items).map(Optional::ofNullable).allMatch(Optional::isPresent);
}

But the same may be achieved with much shorter Object::nonNull:

static boolean allNonNulls(Object ... items) {
    return Stream.of(items).allMatch(Objects::nonNull);
}

CodePudding user response:

Just technically what you want can be achieved the following way

if (Optional.ofNullable(getFirstData).isPresent() && Optional.ofNullable(getSecondData).isPresent() ) {
 ... doing my work here
} else {
  ... doing my else work here
}

But as other commenters have already pointed out, it does not seem wise to do so.

  • Related