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

java 8 stream using filter and count

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

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

我需要获取状态不是“2”或 null 的员工数。

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

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

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

重要的是check first if the status is not null then only we would be able to use the equals method on status,否则我们会得到NullPointerException。您也不需要向 0l 声明计数,count() 将在未找到匹配项时 return 您为 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();