How to skip mapping an element if condition not satisfied

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?

Answer

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
}