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?
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With