提问者:小点点

如何摆脱NullPointerException方法使用流API和可选?[重复]


给定以下任务。我们有一个员工和一个公司类。员工类的每个实例都存储在公司类中的数组员工[]员工中。我需要一个方法,通过id在数组员工[]员工中查找员工的实例。

我设法编写了以下代码:

public class Employee {
    protected final int id;
    protected String name;

    public Employee(int id, String name) {
        this.id = id;
        this.name= name;
    }
    public int getId() {
        return id;
    }
}

public class Company {
    private Employee[] employees;
    private int size;
    private static final int defaultCapacity = 5;
    
    public Company() {
        this(defaultCapacity);
    }
    
    public Company(int capacity) {
        if (capacity <= 0)
             throw new RuntimeException("capacity is required");
        employees = new Employee[capacity];
    }

    public Employee findEmployee(int id) {
        for (int i = 0; i < size; i++) {
            if(employees[i].getId() == id) {
                return employees[i];
            }
        }
        return null;
    }
}

问题是如果员工[]员工的元素等于null,我的方法public员工find员工(int id)抛出NullPointerException

我如何重写方法公共员工find员工(int id)使用流API和可选为了摆脱NullPointerException在方法public员工find员工(int id)


共1个答案

匿名用户

像这样的东西:

public Optional<Employee> findEmployee(int id) {
    return Stream.of(employees)
            .filter(Objects::nonNull) // <---------------
            .filter(employee -> employee.getId() == id)
            .findFirst();
}

如果没有找到结果,这将返回一个空的可选。第一个过滤器将过滤所有非空员工,然后第二个过滤器将检查id。

如果您想获取员工而不是可选,那么您可以使用:

public Employee findEmployee(int id) {
    return Stream.of(employees)
            .filter(Objects::nonNull)
            .filter(employee -> employee.getId() == id)
            .findFirst()
            .orElse(null);
}

或者如果你想深入,你甚至在没有找到员工的情况下抛出异常,例如:

public Employee findEmployee(int id) {
    return Stream.of(employees)
            .filter(Objects::nonNull)
            .filter(employee -> employee.getId() == id)
            .findFirst()
            .orElseThrow(() -> new RuntimeException("No employee found."));
}