2

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
  • First of all, check how you are instantiating your ArrayList. If that code is correct it should be updated to "new ArrayList<>()" (note the capital A). Commented Oct 1, 2021 at 6:48
  • I initiated the ArrayList in correct syntax. Commented Oct 1, 2021 at 6:52

3 Answers 3

4

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();
Sign up to request clarification or add additional context in comments.

2 Comments

Is it better to use "Predicate" instead of writing Lamda expression inside the Filter?
Yeah, I mean Its good practice in the situation when you have a really big expression or you want to reuse same expression elsewhere
1

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.

Comments

1

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();

    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.