使用过滤器和计数的java 8流

问题描述 投票:0回答:3

我有一个名为employee的数组列表。

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

我需要获取状态不为“2”或空的员工数量。

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

在上面的查询中出现类似“lambda表达式不能在求值表达式中使用”的错误,请帮我解决这个错误。

员工列表包含类似的值

 empId  Status
  1       3
  2       4
  3       null

如果状态列不包含空值,则工作正常。

java-8 java-stream
3个回答
3
投票

重要的是

check first if the status is not null then only we would be able to use the equals method on status
,否则我们会得到
NullPointerException
。您也不需要向
0l
声明计数,当未找到匹配项时,
count()
将返回 0。

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

1
投票

如果 Employee 具有

status = null
,它不起作用的原因是您尝试对 null 对象执行
.equals()
操作。在尝试调用 .equals() 操作之前,您应该验证
status
不等于 null,以避免空指针。


0
投票

如果您想使用 java Stream API 查找具有特定项目经理的项目数量,那么您就来吧。

public Long listOfProjectWorkingWithPM(){

   return getAllEmployees()
            .stream()
            .flatMap(pm->pm.getProjects().stream())
            .filter(project -> "Robert Downey Jr".equalsIgnoreCase(project.getProjectManager()))
            .count();

}
© www.soinside.com 2019 - 2024. All rights reserved.