You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java 8 Stream处理员工列表时遇空指针异常,如何跳过异常元素继续处理剩余元素?

解决Java Stream因NullPointerException中断的问题

嘿,这个问题我之前也碰到过——当Stream里的元素属性为null时,直接调用方法肯定会炸NPE,导致整个流直接终止,剩下的元素都没法处理了。你这里就是第4个员工的name是null,x.getName().length()这一步直接触发了异常。

要搞定这个很简单,只需要在filter里先把name为null的元素过滤掉,再判断姓名长度。推荐用Objects.nonNull()工具类来做非空判断,代码更简洁规范。

下面是修改后的完整可运行代码:

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

public class EmployeeTest {
    public static void main(String[] args) {
        List<Employee> empList = new ArrayList<>();
        createEmpList(empList);
        List<Integer> employeeIds = empList.stream()
                // 先排除name为null的元素,再判断长度条件
                .filter(emp -> Objects.nonNull(emp.getName()) && emp.getName().length() > 3)
                .map(Employee::getId) // 用方法引用更简洁
                .collect(Collectors.toList());
        System.out.println(employeeIds); // 输出 [1, 2, 3, 5, 6, 7, 8]
    }

    private static void createEmpList(List<Employee> empList) {
        Employee e1 = new Employee("siddu", 1, "Hyderabad", 70000);
        Employee e2 = new Employee("Swami", 2, "Hyderabad", 50000);
        Employee e3 = new Employee("Ramu", 3, "Bangalore", 100000);
        Employee e4 = new Employee(null, 4, "Hyderabad", 65000);
        Employee e5 = new Employee("Krishna", 5, "Bangalore", 160000);
        Employee e6 = new Employee("Naidu", 6, "Poland", 250000);
        Employee e7 = new Employee("Arun", 7, "Pune", 45000);
        Employee e8 = new Employee("Mahesh", 8, "Chennai", 85000);
        empList.add(e1);
        empList.add(e2);
        empList.add(e3);
        empList.add(e4);
        empList.add(e5);
        empList.add(e6);
        empList.add(e7);
        empList.add(e8);
    }
}

// 补充Employee类的定义(原代码里可能没贴出来,编译需要这个)
class Employee {
    private String name;
    private int id;
    private String city;
    private int salary;

    public Employee(String name, int id, String city, int salary) {
        this.name = name;
        this.id = id;
        this.city = city;
        this.salary = salary;
    }

    public String getName() {
        return name;
    }

    public int getId() {
        return id;
    }
}

核心修改点:

  • 在filter中添加Objects.nonNull(emp.getName())作为第一个判断条件,利用逻辑与&&的短路特性——如果name为null,就不会执行后面的length()调用,完美避免NPE;
  • 这样流会自动跳过name为null的员工(也就是id为4的那个),继续处理剩下的符合条件的元素,最终输出你想要的结果。

内容的提问来源于stack exchange,提问作者durgaPrasad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 20:59:11