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

时间:2018-02-23 18:40:13

标签: java java-stream

我有这堂课:

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

1 个答案:

答案 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);
}