Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java 8, when I use stream() and filter(), can I keep objects related to the main one (as opposed to the object itself)?

I'm using Java 8. I realize I can cycle through a collection of objects and keep certain ones taht match a condition, which I've done below

final List<Organization> orgs = user.getOrganizations().stream().filter(org -> org.getParentOrg() != null && org.getParentOrg().getOrganizationType().isParent())
                    .collect(Collectors.toCollection(() -> new ArrayList<Organization>()));

but what if in some instances, I don't want to keep the object itself, but an object related to it? That is if condition A is met, I want to keep "org", but if condition "B" is met, I want to keep "org.getParentOrg()", which is of the same type. Does Java 8 provide a way to deal with this type of situation?

like image 804
satish Avatar asked Dec 17 '25 18:12

satish


1 Answers

I would use Stream.map, along with the ternary operator and a previous Stream.filter to discard elements that match neither conditionA nor conditionB:

List<Organization> orgs = user.getOrganizations().stream()
    .filter(org -> conditionA || conditionB)
    .map(org -> conditionA ? org : org.getParentOrg())
    .collect(Collectors.toCollection(ArrayList::new));
like image 107
fps Avatar answered Dec 19 '25 23:12

fps



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!