java将一种可选类型转换为另一种可选类型

时间:2018-10-23 15:48:19

标签: java java-8 optional

我必须将Optional<EmployeeModel>对象转换为Optional<EmployeeDto>,并且正在寻找比以下两个更好/更干净的选项。

选项1:

public Optional<EmployeeDto> findById(String employeeId){
    Optional<EmployeeModel> employeeModel = employeeService.findById(employeeId);
    return Optional.ofNullable(toEmployeeDto(toEmployeeDto.orElse(null)));
}
private EmployeeDto toEmployeeDto(EmployeeModel employeeModel) {
    if(employeeModel != null) {//We need this because orElse passes null
        //return EmployeeDto (convert EmployeeModel to dto)
    } else {
        return null;
    }
}

选项2:

public Optional<EmployeeDto> findById(String employeeId){
    Optional<EmployeeModel> employeeModel = employeeService.findById(employeeId);
    if(employeeModel.isPresent()) {
        return Optional.of(toEmployeeDto(employeeModel.get()));
    } else {
        return Optional.empty();
    }
}
private EmployeeDto toEmployeeDto(EmployeeModel employeeModel) {
    //isPresent()check already done so no null checks
    //return EmployeeDto (convert EmployeeModel to dto)
}

我不能直接使用Optional.map(),因为EmployeeModel中的null对象可以为空(即Optional包装的employeeService)。另外,我只是在map()类中检查Optional方法的源代码,该代码执行以下检查:

Objects.requireNonNull(mapper);

简而言之,我的问题是我们可以将null对象传递给Optional的{​​{1}}方法吗?如果是,为什么map()签入源代码?

1 个答案:

答案 0 :(得分:5)

使用Optional.map()方法:

  

如果存在值,则将提供的映射函数应用于该值,如果结果为非null,则返回描述结果的Optional。否则,返回一个空的Optional

public Optional<EmployeeDto> findById(String employeeId){
    Optional<EmployeeModel> employeeModel = employeeService.findById(employeeId);
    return employeeModel.map(this::toEmployeeDto);
}
private EmployeeDto toEmployeeDto(EmployeeModel employeeModel) {
    //employeeModel will not be null, so:
    //return EmployeeDto (convert EmployeeModel to dto)
}