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條經驗 獲得超6個贊
為了讓您了解這在 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 的作用。我真的很喜歡它避免樣板映射代碼。
添加回答
舉報