gpt4 book ai didi

java - 使用 java Stream api 更新对象的嵌套列表

转载 作者:行者123 更新时间:2023-12-02 11:35:50 31 4
gpt4 key购买 nike

我有这门课:

public class StructUserType extends UserType {

MembersList membersList = new MembersList();

public List<Member> getMembers() {
return Collections.unmodifiableList(membersList.members);
}

static class MembersList {
List<Member> members = new ArrayList<>();
}

public static class Member implements Identifiable {
private Integer id;
private String name;
//getters and setters
}
}

我有一个对象的列表:

List<UserType> userTypes = new ArrayList<>();

我想要更新等于某个 id 的 Member 对象。例如,通过id更新member的name字段。如何使用 stream api 更新嵌套列表?

更新:

我这样做了:

在类StructUserType中我创建了一个方法:

void updateMember(Member member) {
membersList.members.stream()
.filter(m -> m.getId().equals(member.getId()))
.findFirst()
.ifPresent(m -> {
m.setName(member.getName());
m.setUserTypeId(member.getUserTypeId());
});
}

还为外部客户端创建了一个公共(public)方法:

public void updateMemberOfStructUserType(StructUserType.Member member) {
userTypes.stream()
.filter(StructUserType.class::isInstance)
.map(StructUserType.class::cast)
.filter(st -> st.getMembers()
.stream()
.anyMatch(m -> m.getId().equals(member.getId())))
.findFirst()
.ifPresent(structUserType -> structUserType.updateMember(member));
}

最佳答案

您可以在公共(public)更新方法中平面映射userTypes,并将成员流传递给公共(public)私有(private)updateMember 方法:

private void updateMember(Member member, Stream<Member> membersStream){
membersStream.filter(m -> m.getId().equals(member.getId()))
.findFirst()
.ifPresent(m -> {
m.setName(member.getName());
m.setUserTypeId(member.getUserTypeId());
});
}

void updateMember(Member member) {
updateMember(member, membersList.members.stream());
}

public void updateMemberOfStructUserType(StructUserType.Member member) {
Stream<Member> membersStream = userTypes.stream()
.filter(StructUserType.class::isInstance)
.map(StructUserType.class::cast)
.flatMap(st -> st.getMembers().stream());
updateMember(member, membersStream);
}

关于java - 使用 java Stream api 更新对象的嵌套列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48954302/

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