網頁

2018/12/7

Java 8 用Optional來檢查null並用orElseThrow()丟出例外錯誤

使用Optional來檢查物件是否為null,若為null則丟出例外。

用來做為參數的Department類別

Department.java

class Department {

    private String departmentName;
    private List<Employee> employeeList;
    
    public Department(String departmentName, List<Employee> employeeList) {
        super();
        this.departmentName = departmentName;
        this.employeeList = employeeList;
    }
    
    public String getDepartmentName() {
        return departmentName;
    }
    public void setDepartmentName(String departmentName) {
        this.departmentName = departmentName;
    }
    public List<Employee> getEmployeeList() {
        return employeeList;
    }
    public void setEmployeeList(List<Employee> employeeList) {
        this.employeeList = employeeList;
    }

}

Employee.java

class Employee {

    private String name;
    
    public Employee(String name) {
        this.name = name;
    }
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

下面的方法傳入Department物件,並中取得所有Employee的名字。

public class Main {

    public static void main(String[] args) throws Exception {

        Employee employee1 = new Employee("Alice");
        Employee employee2 = new Employee("Mike");
        Department department = new Department("IT", Arrays.asList(employee1, employee2));
        
        List<String> employeeNameList = getEmployeeNameList(department);
        employeeNameList.forEach(System.out::println);
    }

    public static List<String> getEmployeeNameList(Department department) throws Exception {
        
        List<Employee> employeeList = Optional.ofNullable(department)
                .orElseThrow(() -> new Exception("department is null"))
                .getEmployeeList();
        
        return Optional.ofNullable(employeeList)
                .orElse(new ArrayList<>())
                .stream()
                .filter(e -> e.getName() != null && e.getName().length() > 0)
                .map(e -> e.getName()).collect(Collectors.toList());
        
    }

}

參考:

沒有留言:

張貼留言