遍历列表并将项目添加到另一个

时间:2019-01-31 18:25:30

标签: java

我在List中得到了一些数据,如下所示:

groupCode    |    groupMember
-------------------------------
001           |    name1
-------------------------------
001           |    name2
-------------------------------
002           |    name3
-------------------------------
003           |    name4

在一些I组可以有更多的组成员。所以我需要遍历列表并以这种方式对数据进行排序:

001 (List)
- name1 (List inside List)
- name2
002 (List)
- name3
- name4

我使用类Group和GroupMember。我该怎么办?

public class Group {

    private String groupCode;
    private GroupMember groupMember;

...我不能使用private List<GroupMember> groupMember;这里

public class GroupMember {

    private String name;

    public String getName() {
        return name;
    }

1 个答案:

答案 0 :(得分:1)

如果nvidia-settings是原始的待处理列表,其内容为:

members

可通过以下代码实现:

Group [001, GroupMember [name1]]
Group [001, GroupMember [name2]]
Group [002, GroupMember [name3]]
Group [003, GroupMember [name4]]

然后,可以通过Java stream API的帮助完成所需的分组:

class GroupMember {
    private String name;


    public GroupMember(String name) {
        super();
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return String.format("GroupMember [%s]", getName());
    }


}

class Group {

    private String groupCode;
    private GroupMember groupMember;

    public Group(String groupCode, GroupMember groupMember) {
        super();
        this.groupCode = groupCode;
        this.groupMember = groupMember;
    }

    public String getGroupCode() {
        return groupCode;
    }

    public void setGroupCode(String groupCode) {
        this.groupCode = groupCode;
    }

    public GroupMember getGroupMember() {
        return groupMember;
    }

    public void setGroupMember(GroupMember groupMember) {
        this.groupMember = groupMember;
    }

    @Override
    public String toString() {
        return String.format("Group [%s, %s]", getGroupCode(), getGroupMember());
    }


}


...

List<Group> members = new ArrayList<>();

members.add(new Group("001", new GroupMember("name1")));
members.add(new Group("001", new GroupMember("name2")));
members.add(new Group("002", new GroupMember("name3")));
members.add(new Group("003", new GroupMember("name4")));


在这种情况下,分组的内容将是:

import static java.util.stream.Collectors.*;

...

Map<String, List<GroupMember>> grouped = members
                .stream()
                .collect(groupingBy(Group::getGroupCode,
                                    mapping(Group::getGroupMember, toList())));

根据需要。