I have to filter a list, based on the value of an attribute. I also have to filter a nested list, based on one of its attributes, and likewise for another nested list. I wondered how this might be possible in a stream.
Example:
- I want to filter a List of Foo's, retaining only those where Foo.type = "fooType".
- Within these retained Foo's, I wish to filter a list of Bar's on Bar.type = "barType", retaining only those which satisfy the given condition.
- I then want to filter the list of NestedAttribute's on NestedAttribute.id = "attributeID", only retaining those which match this condition.
- Within these retained Foo's, I wish to filter a list of Bar's on Bar.type = "barType", retaining only those which satisfy the given condition.
I want to return the list of foo's, from this.
void test() {
List<Foo> listOfFoos;
for(Foo foo : listOfFoos) {
if(foo.getType().equalsIgnoreCase("fooType")) {
// If foo matches condition, retain it
for(Bar bar : foo.getBars()) {
if(bar.getType().equalsIgnoreCase("barType")) {
// If Bar matches condition, retain this Bar
for(NestedAttribute attribute : bar.getNestedAttributes()) {
if(attribute.getId().equalsIgnoreCase("attributeID")) {
// retain this attribute and return it.
}
}
} else {
// remove bar from the list
foo.getBars().remove(bar);
}
}
}else {
// remove Foo from list
listOfFoos.remove(foo);
}
}
}
@Getter
@Setter
class Foo {
String type;
List<Bar> bars;
}
@Getter
@Setter
class Bar {
String type;
List<NestedAttribute> nestedAttributes;
}
@Getter
@Setter
class NestedAttribute {
String id;
}
I have tried this:
listOfFoos = listOfFoos.stream()
.filter(foo -> foo.getType().equalsIgnoreCase("fooType"))
.flatMap(foo -> foo.getBars().stream()
.filter(bar -> bar.getType().equalsIgnoreCase("barType"))
.flatMap(bar -> bar.getNestedAttributes().stream()
.filter(nested -> nested.getId().equalsIgnoreCase("attributeID"))
)
).collect(Collectors.toList());
listOfFoos.stream.filter(...). What's the output? The listOfFoos?filter.