I need to run filtering on nested Lists and return a List of items from back
I will put a sample code here with my model
import lombok.Data;
import java.util.List;
import java.util.stream.Collectors;
class Scratch {
public static void main(String[] args) {
ParentModel parent = new ParentModel();
List<Information> informationList = parent.getChildDatas().stream()
//Filtering null && empty grandchild
.filter(childData -> childData.getGrandChildDatas() !=null && !childData.getGrandChildDatas().isEmpty())
.flatMap(childData -> childData.getGrandChildDatas().stream() )
//Filtering null && empty information
.filter(grandChild -> grandChild.getInformations() !=null && !grandChild.getInformations().isEmpty())
.flatMap(grandChild-> grandChild.getInformations().stream())
//filtering key
.filter(information -> information.getKey().equals("SOMETHING"))
.collect(Collectors.toList());
}
@Data
static class ParentModel {
private List<ChildModel> childDatas;
}
@Data
static class ChildModel {
private List<GrandChildModel> grandChildDatas;
}
@Data
static class GrandChildModel {
private List<Information> informations;
}
@Data
static class Information{
private String info1;
private String info2;
private String key;
}
}
So here you can see, I'm filtering and mapping it back to child streams two times.
Is there alternate way to achieve what I'm trying to do here ??