Convert this null check to java 8 Optional

Viewed 114

I am unable to understand how to remove the below null check by using Java 8 Optional

for (A objA : listOfObjectsA) {
    if (objA.getStringField() == null) continue;
        // some code to do if not null
}
4 Answers

You don't have to use Optionals for that. You can filter the null elements using a Stream:

listOfObjectsA.stream()
              .filter(objA -> objA.getStringField() != null)
              .forEach (... do something  ...);

To use Optional you can write Optional.ofNullable(objA.getStringField()).isPresent(), but that seems pointless.

You could replace your code with Java8 style with streams and Optional. But I presonally think that in this concrete case, this is not better that POJO (which is much more simplier and readable):

Optional.ofNullable(listOfObjectsA).orElse(Collections.emptyList()).stream()
        .filter(Objects::nonNull)
        .filter(objA -> Objects.nonNull(objA.getStringField()))
        .forEach(objA -> {
            // some code to do if not null
        });

If you're sure, that given list cannot be null and each element objA cannot be null as well, then you can definitely avoid some useless checks in this case:

listOfObjectsA.stream()
        .filter(objA -> Objects.nonNull(objA.getStringField()))
        .forEach(objA -> {
            // some code to do if not null
        });

if "some code to do if not null" only operates on objA.getStringField() then you can do:

listOfObjectsA.stream()
              .map(A::getStringField)
              .filter(Objects::nonNull)
              .forEach(e -> ...);

However, if you still want to have access to the A elements then as the other answers have shown you have no choice but to perform an explicit objA.getStringField() != null:

listOfObjectsA.stream()
              .filter(a -> a.getStringField() != null)
              .forEach(a -> ...);

Ideally without optional, you can do

listOfObjectsA.stream().filter(objA -> objA.getStringField() != null)
                       .forEach(objA -> { /* some code to do if not null*/ });
Related