java 8 stream using filter and count

Viewed 1468

I have a array list named employee.

List<Employee> employee = new ArrayList<Employee>();

I need to get the count of employees whose status is not "2" or null.

long count = 0l;
count = employee.stream()
.filter(p->!(p.getStatus().equals("2")) || p.getStatus() == null).count();

In the above query getting error like "lambda expression cannot be used in evaluation expression", Please help me to resolve this error.

The list employee contains values like

 empId  Status
  1       3
  2       4
  3       null

If the status column doesn't contains null value it is working fine.

2 Answers

It's important to check first if the status is not null then only we would be able to use the equals method on status, else we will get NullPointerException. You also don't need to declare count to 0l, count() will return you 0 when no match is found.

List<Employee> employee = new ArrayList<Employee>();
// long count = 0l;

// Status non null and not equals "2" (string)
ling count = employee.stream()
    .filter(e ->  Objects.nonNull(e.getStatus()) && (!e.getStatus().equals("2")))
    .count();

The reason it doesn't work if an Employee has status = null is because you are trying to perform the .equals() operation on a null object. You should verify that status is not equal to null before trying to invoke the .equals() operation to avoid null pointers.

Related