Convert this null check to Java 8 optional
•
Java
I can't understand how to delete the following null check using java 8 option
for (A objA : listOfObjectsA) { if (objA.getStringField() == null) continue; // some code to do if not null }
Solution
If "some code is not null" is only valid for obja Getstringfield(), you can do the following:
listOfObjectsA.stream() .map(A::getStringField) .filter(Objects::nonNull) .forEach(e -> ...);
However, if you still want to access the a element, as the other answers show, you have no choice but to execute explicit obja getStringField()!= null:
listOfObjectsA.stream() .filter(a -> a.getStringField() != null) .forEach(a -> ...);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码