gpt4 book ai didi

java - 如果条件不满足,如何跳过映射元素

转载 作者:行者123 更新时间:2023-12-05 00:43:43 27 4
gpt4 key购买 nike

假设我有以下内容

public class UserEntity{
String id;
List<String> relatedEntity;
}

public class EmployeeEntity{
String id;
String name;
Boolean isActive;
List<String> relatedEntityDetails;
}

现在有了一个 UserEntity 列表,我必须映射到一个 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;
}

现在,一切正常,但是当数据库中不存在 EmployeeEntity 或 isActive = false 时,我需要处理这种情况,在这些情况下,应该跳过 map(),所以如果有 3 个元素的列表UserEntity 并且对于其中一位用户,一名员工未处于 Activity 状态,则返回的 List 应该只有 2 个元素。

关于如何添加该行为的任何建议?

最佳答案

制作 mapToEmployee返回 Optional<EmployeeEntity> ,并过滤一个不为空的:

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
}

关于java - 如果条件不满足,如何跳过映射元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68894423/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com