简体   繁体   English

如何在Java中将数据从一个对象列表复制到另一个对象?

[英]How to copy data from one list of objects to another in java?

I have the following 2 objects Team and Group . 我有以下两个对象TeamGroup I have standard getters setters and toString methods in each of these classes and not allowed to modify them. 我在每个这些类中都有标准的getters setters和toString方法,并且不允许对其进行修改。

public class Team { 
  private List<Team> teams;
  private List<TeamMember> members;
  private String teamId;    
}

public class Group {    
  private List<GroupMember> groupMember;
  private List<Group> groups;
  private String groupId;
}

Team can have a List<Team> type of a list as an attribute where List<Group> can have a List<Group> as an attribute. 团队可以具有List<Team>类型作为属性,而List<Group>可以具有List<Group>作为属性。

example list of Teams look like follows: 团队示例列表如下所示: 在此处输入图片说明

I want to create the list of Groups which reflects the same structure of TeamList . 我想要创建反映TeamList相同结构的Groups列表。

This is what I have got so far. 到目前为止,这就是我所得到的。

@Service
public class GroupService {

@Autowired
TeamService teamService;

public List<Group> createGroupList(){

    List<Group> groups = Collections.emptyList();

    List<Team> teams = teamService.createTeamList();

    if (teams != null && !teams.isEmpty()) {

        groups = teams.stream().map(t -> {

            Group group = new Group();
            group.setGroupId(t.getTeamId());

            //this is to be modified
            group.setGroups(getSubgroups(teams, group.getGroupId()));

            return group;

        }).collect(Collectors.toList());

    }

    return groups;
}



private List<Group> getSubgroups(List<Team> teams, String parentGroupName) {

    Optional<Team> parentTeam = teams.stream()
            .filter(t -> t.getTeamId().equalsIgnoreCase(parentGroupName)).findFirst();

    if(parentTeam.isPresent()){

        List<Team> subTeams = new ArrayList<>();
        List<Group> lstOfGroups = new ArrayList<>();

        System.out.println("parentname " + parentTeam.get().getTeamId());


        if(parentTeam.get().getTeams() != null){
            parentTeam.get().getTeams().stream().forEach(r -> {
                subTeams.add(r);
            });
        }

        subTeams.stream().forEach(st -> {
            Group gr = new Group();
            gr.setGroupId(st.getTeamId());
            lstOfGroups.add(gr);    
        });

        return lstOfGroups;

    }
    return null;            

 }

}

My idea is to modify the getSubgroups method to set the subgroups correctly for each given path.(eg: getSubgroubs can return team2 with all it's subgroups set until team7) I know I have to use recursion but I am struggling to find the solution. 我的想法是修改getSubgroups方法以正确设置每个给定路径的子组。(例如:getSubgroubs可以返回设置了所有子组的team2,直到team7为止),我知道我必须使用递归,但是我一直在努力寻找解决方案。 How can I achieve this? 我该如何实现?

EDIT 编辑

I have updated my code and now I can access the first level of children and not the other levels yet 我已经更新了我的代码,现在我可以访问第一级儿童,但尚未访问其他儿童

You can just create a single method to copy one into the other and call it recursively: 您可以只创建一个方法将一个方法复制到另一个方法中,然后递归调用它:

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;
}

so you can do 所以你可以做

List<Group> groups = teamService.getTeams()
                         // you should return an empty list if no elements are present
                         .stream()  
                         .map(this::toGroup) // initial call
                         .collect(toList());

You might also want to look into mapstruct which can automatically generate simple mappers. 您可能还想研究一下可自动生成简单映射器的mapstruct

To give you an idea how this would look in mapstruct: 让您知道在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);
}

The actual code will be generated. 实际的代码将被生成。 If the classes have properties with the same name (eg if the ids were called id for both Team and Group? ), a @Mapping annotation is not needed for it. 如果类具有相同名称的属性(例如,如果IDS被称为id两个TeamGroup? ),一个@Mapping不需要为它注释。

Then, you can @Autowire this as a component and use it. 然后,您可以@Autowire作为组件使用它。

@Component
class YourGroupService implements GroupService {
    @Autowired TeamGroupMapper mapper;
    @Autowired TeamService teamService;

    public List<Group> getGroups() {
        return mapper.toGroups(teamService.getTeams());
    }
}

I'm sure this code won't actually work, but it should give you an idea of what mapstruct does. 我确定这段代码实际上不会起作用,但是它应该使您了解mapstruct的作用。 I really like it to avoid boilerplate mapping code. 我真的很喜欢它以避免样板映射代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将输入数据从一个文件复制到另一个文件? 在 java - how to copy input data from one file to another one? in java Java 8 - 如何将属性值从一个列表复制到另一个列表? - Java 8 - how to copy a property value from one list to another? 如何将值从一个列表复制到另一个具有不同对象的列表 - How to copy value from one list to another list having different objects 如何在java中将S3对象列表从一个文件夹移动/复制到文件夹? - How to move/copy list of S3 Objects from one folder to folder in java? java 中从一个列表到另一个列表的数据 - Data from one list to another in java 如何将数据从一个表复制到另一个表,然后使用 Java 删除第一个表中的数据? - How to copy data from one table to another and then delete that data in first table using Java? 在Java中将数据从一个数据库服务器复制到另一数据库服务器 - Data Copy From one db server to another db server in java Java Apache Arrow 将数据从一个 VectorSchemaRoot 复制到另一个 - Java Apache Arrow Copy data from one VectorSchemaRoot to another 如何将数据列表从一个数据库复制到另一个数据库而不获取密钥为 0 1 2 3 等等 - How to copy list of data from one database to another database without getting key as 0 1 2 3 and so on Java泛型,将一个列表复制到另一个 - Java generics, copy one list to another
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM