2 回答
TA贡献1906条经验 获得超10个赞
您可以只创建一个方法来将一个方法复制到另一个方法中并递归调用它:
public Group toGroup(Team team) {
Group result = new Group(team.teamId());
// this is missing in your sample code
result.setGroupMembers(transform(team.getTeamMembers());
List<Group> subGroups = team.getTeams().stream()
.map(this::toGroup) // recursive call to this method
.collect(toList());
result.setSubgroups(subGroups);
return result;
}
所以你可以做
List<Group> groups = teamService.getTeams()
// you should return an empty list if no elements are present
.stream()
.map(this::toGroup) // initial call
.collect(toList());
您可能还想查看可以自动生成简单映射器的mapstruct。
TA贡献1772条经验 获得超5个赞
为了让您了解这在 mapstruct 中的外观:
@Mapper(componentModel="spring")
interface TeamGroupMapper {
@Mappings({
@Mapping(source="teamId", target="groupId"),
@Mapping(source="teams", target="groups"),
@Mapping(source="teamMembers", target="groupMembers")
})
Group toGroup(Team team);
List<Group> toGroups(List<Team> teams);
GroupMember toGroupMember(TeamMember teamMember);
}
将生成实际代码。如果类具有同名的属性(例如,如果id为Team和调用了 id Group?),@Mapping则不需要对其进行注释。
然后,您可以将@Autowire其作为组件使用。
@Component
class YourGroupService implements GroupService {
@Autowired TeamGroupMapper mapper;
@Autowired TeamService teamService;
public List<Group> getGroups() {
return mapper.toGroups(teamService.getTeams());
}
}
我确信这段代码实际上不会工作,但它应该让您了解 mapstruct 的作用。我真的很喜欢它避免样板映射代码。
添加回答
举报