简体   繁体   中英

java convert one optional type to another optional type

I have to convert an Optional<EmployeeModel> object to Optional<EmployeeDto> and I am looking for some better/cleaner options than the below two.

Option1:

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

Option2:

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

I can't use Optional.map() directly as EmployeeModel object can be null (ie, null wrapped by Optional ) from the employeeService . Also, I was just checking source code for map() method inside Optional class which does the below check:

Objects.requireNonNull(mapper);

In short, my question is that can we pass null objects to Optional 's map() method? If yes, why does the Objects.requireNonNull() check in the source code?

Use the Optional.map() method:

If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty 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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM