gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:19:04 25 4
gpt4 key购买 nike

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

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 stream 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]]}

根据需要。

关于java - 遍历列表并将项目添加到另一个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54467024/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com