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?
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);
}