【问题标题】:How to get rid of NullPointerException in a method using Streams API and Optional?如何在使用 Streams API 和 Optional 的方法中摆脱 NullPointerException?
【发布时间】:2022-11-22 21:21:31
【问题描述】:

给出以下任务。 我们有一个 Employee 和一个 Company 类。 Employee类的每个实例都存储在Company类的数组Employee[] employees中。我需要一种方法,它可以在 id 的数组 Employee[] employees 中找到 Employee 的实例。

我设法编写了以下代码:

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;
    }
}

问题是我的方法public Employee findEmployee(int id)抛出空指针异常如果 Employee[] employees 的一个元素等于 null。

问题:

  1. 如何重写方法public Employee findEmployee(int id)使用 Streams API 和可选为了在方法 public Employee findEmployee(int id) 中摆脱 NullPointerException?

【问题讨论】:

    标签: java nullpointerexception java-stream option-type


    【解决方案1】:

    是这样的:

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

    如果没有找到结果,这将返回一个空的Optional。

    如果你想获得 Employee 而不是 Optional,那么你可以使用:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 2022-01-04
      相关资源
      最近更新 更多