Reputation: 22422
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?
Upvotes: 4
Views: 12039
Reputation: 159086
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 emptyOptional
.
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)
}
Upvotes: 8