简体   繁体   中英

remove element from inner list using stream api java

I have a document object in which it has a list of model class , which has cascaded inner lists of further model classes .

The hierarchy is as follows

Document --> MODEL_1 --> MODEL_2 --> MODEL_3 --> MODEL_4

What i need to do is from this document object - remove all such MODEL_4 items which have their model_name as "ABC"

What i have tried currently is

List<MODEL_1> model1List = document.getModelList();

for (int i = 0; i < model1List.size(); i++) {               
    MODEL_1 model1 = model1List.get(i);
    List<MODEL_2> model2List = model1.getModel_2list();

        for (int j = 0; j < model2List.size(); j++) {
            MODEL_2 model2 = model2List.get(j);
            List<MODEL_3> model3List = model2.getModel_3List();

            for (int z = 0; z < model3List.size(); z++) {
                MODEL_3 model3 = model3List.get(z);         
                List<MODEL_4> model4List = model3.getModel4List();

                model4List.removeIf(element -> element.getModelname().equals("ABC"));
            }
        }
    }
}

it works - but i know that it is not optimum coding.

I tried writing a predicate - to filter a such element - but could not figure out how to write predicate for inner lists.

Does any one have idea about predicate for inner lists ..

any help is appreciated , thank you in advance

I think yours is a quite straight-forward solution, which cannot be optimized (much or at all) concerning performance, but maybe concerning readability with respect to the amount of lines of code.

A stylistic improvement may be this:

model1List.forEach(model1 -> 
    model1.getModel2List().forEach(model2 ->
        model2.getModel3List().forEach(model3 -> 
            model3.getModel4List().removeIf(model4 -> model4.getModelName().equals("ABC"))
        )
    )
);

Note that you need Java 8 for it, but you obviously have that (at least) due to your update to removeIf ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM