I have an object, Person
, which has two properties Name
and Status
. From a list of objects I hope to filter out the Person
objects with a status of In Progress
. Here is my code:
personList.stream().filter(
t -> t.getStatus().equalsIgnoreCase(
"In Progress")).collect(Collectors.toList());
But the code is throwing a nullpointerexception
error. When I checked, I saw that a few of the objects with In Progress
status had null values. How do we handle this in lambda?
You can just reverse the 2 "operands" of the equals
method:
"In Progress".equalsIgnoreCase(t.getStatus())
This way since "In Progress"
can never be null, there won't be an NPE!
Try filtering out objects with null statuses
personList
.stream()
.filter(t -> t.getStatus() != null)
.filter(t -> t.getStatus().equalsIgnoreCase("In Progress"))
.collect(Collectors.toList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With