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

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


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

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

最佳答案

如果members是要处理的原始列表,其内容为:

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


可通过以下代码实现:

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")));




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

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

...

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



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


{001=[GroupMember [name1], GroupMember [name2]], 002=[GroupMember [name3]], 003=[GroupMember [name4]]}


按要求。

08-06 19:28