我有这堂课:
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
对象:
List<UserType> userTypes = new ArrayList<>();
我想要更新Member
对象,它等于某个id。例如,按ID更新成员的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 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));
}
答案 0 :(得分:1)
您可以在公共更新方法中对userTypes
进行平面映射,并将成员流传递给公共私有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);
}