Reputation: 149
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.
Upvotes: 2
Views: 6155
Reputation: 9
If you want to find number of project having particular project manager using Java stream API then here you go.
public Long listOfProjectWorkingWithPM(){
return getAllEmployees()
.stream()
.flatMap(pm->pm.getProjects().stream())
.filter(project -> "Robert Downey Jr".equalsIgnoreCase(project.getProjectManager()))
.count();
}
Upvotes: 1
Reputation: 3714
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();
Upvotes: 4
Reputation: 140
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.
Upvotes: 1