Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception in Java for null values in lambda expression while filtering [duplicate]

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?

like image 274
sTg Avatar asked Oct 26 '17 09:10

sTg


2 Answers

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!

like image 131
Sweeper Avatar answered Sep 22 '22 15:09

Sweeper


Try filtering out objects with null statuses

personList
  .stream()
  .filter(t -> t.getStatus() != null)
  .filter(t -> t.getStatus().equalsIgnoreCase("In Progress"))
  .collect(Collectors.toList());
like image 44
TheRock3t Avatar answered Sep 24 '22 15:09

TheRock3t