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 (i.e., 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?