Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert this null check to java 8 Optional

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
}
like image 393
Saad Avatar asked Sep 10 '26 14:09

Saad


1 Answers

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 -> ...);
like image 136
Ousmane D. Avatar answered Sep 12 '26 03:09

Ousmane D.