简体   繁体   English

使用流api java从内部列表中删除元素

[英]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文档 --> 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"我需要做的是从此文档对象中删除所有这些模型名称为“ABC”的 MODEL_4 项目

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 ...请注意,您需要 Java 8,但显然(至少)由于您更新removeIf ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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