Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get parent object from stream

I have this class:

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;

        public Integer getId() {
            return id;
        }
    }    
} 

And I have a List object:

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

I want find Member which is equal to a certain id. I tried as follows:

Integer id = 1;
userTypes.stream()
                .filter(StructUserType.class::isInstance)
                .map(StructUserType.class::cast)
                .forEach(structUserType -> {
                    structUserType.getMembers()
                            .stream()
                            .filter(m -> m.getId() == id)
                            .findFirst().orElse(null);
                });

I want, when the filter in the internal stream runs and finds the first member, to return the parent element that this member contains, those UserType.

Analog in the classical style:

for (UserType userType : userTypes) {
            if (userType instanceof StructUserType) {
                List<StructUserType.Member> members = ((StructUserType) userType).getMembers();

                for (StructUserType.Member member : members) {
                    if (member.getId() == id) {
                        return userType;
                    }
                }
            }
        }
        return null;
like image 848
All_Safe Avatar asked Feb 15 '26 23:02

All_Safe


1 Answers

Replace forEach with filter, to find StructUserType instances that satisfy the condition of the inner stream pipeline. Then get the first element of the Stream, if such exists.

return
   userTypes.stream()
            .filter(StructUserType.class::isInstance)
            .map(StructUserType.class::cast)
            .filter(st -> st.getMembers()
                            .stream()
                            .anyMatch(m -> m.getId().equals(id)))
            .findFirst()
            .orElse(null);
like image 126
Eran Avatar answered Feb 18 '26 13:02

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!