Assuming I have the following
public class UserEntity{
String id;
List<String> relatedEntity;
}
public class EmployeeEntity{
String id;
String name;
Boolean isActive;
List<String> relatedEntityDetails;
}
Now having a list of UserEntity I have to map to a list of EmployeeEntity:
private List<EmployeeEntity> getEmployees(List<UserEntity> users)
return users.stream()
.filter(x-> !x.getRelatedEntity().isEmpty())
.map(this::mapToEmployee)
.collect(Collectors.toList());
}
private EmployeeEntity mapToEmployee(UserEntity userEntity){
// retrieve EmployeeEntity from DB and perform a validations like
// employeeEntity.isActive = true
return employeeEntity;
}
Now, everything works fine, however I need to handle the scenario when EmployeeEntity is not present in db, or isActive = false, in these scenarios, the map() should be skipped, so if there is a list of 3 elements UserEntity and for one of those users, one employee is not active, then the returned List should have only 2 elements.
Any suggestions on how to add that behaviour?
Make mapToEmployee
return an Optional<EmployeeEntity>
, and filter one those that are not empty:
private List<EmployeeEntity> getEmployees(List<UserEntity> users)
return users.stream()
.filter(x-> !x.getRelatedEntity().isEmpty())
.map(this::mapToEmployee)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList());
}
private Optional<EmployeeEntity> mapToEmployee(UserEntity userEntity){
... optional depending on whether it is present in DB and/or is active
}
In any case you NEED to query the databse for every employee so i propose:
private List<EmployeeEntity> getEmployees(List<UserEntity> users)
return users.stream()
.filter(x-> !x.getRelatedEntity().isEmpty())
.map(this::mapToEmployee)
.filter(Optional::isPresent)
.map(Optional::get)
.filter(EmployeeEntity::isActive)
.collect(Collectors.toList());
}
private Optional<EmployeeEntity> mapToEmployee(UserEntity userEntity){
// return the db employee whatsoever, i believe the mapper should not be responssible for logic validation
if (employeeDoesNotExistsInDb) {
return Optional.empty();
}
return employeeEntity;
}
I would advise you to use the mapper as a mapper, not as a mapper + specific validator. That validation should happen later on on the process. It would make the code more clear and more reusable. Also you'll maybe want to rename getEmployees
as getActiveEmployees
EDIT: Thanks to @M A to remind me of the Optional
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With