简体   繁体   English

Java 8如何遍历嵌套的对象列表

[英]Java 8 how to iterate over a nested list of objects

I am new to Java 8 and i have a response object which has a list of detail object and the detail object contains a list of reason object where the reason object has a reason code. 我是Java 8的新手,我有一个响应对象,其中包含一个详细对象列表,而详细对象包含一个原因对象列表,其中原因对象具有原因代码。 I am trying to iterate to the reason object from the response object and search if there is any reason code equal to a given key. 我试图从响应对象迭代到原因对象,并搜索是否有任何等于给定键的原因代码。 Could you please help in how to do that in java 8, with minimum complexity. 您能否以最小的复杂性帮助您在Java 8中做到这一点。 Below is sample way in java 7 not the best approach thou. 下面是Java 7中的示例方法,不是您最好的方法。

 if(response != null && CollectionsUtil.isNotEmpty(response.getDetails())) {

            List<Detail> details = response.getDetails();
            for(Detail det : details) {
                if(CollectionsUtil.isNotEmpty(det.getReasons())) {                  
                    for(Reason reason: det.getReasons()) {
                        if(StringUtils.equalsIgnoreCase("ABC", reason.getReasonCode())) {
                            ///////////call an external method
                        }
                    }

                    }
                }
            }

Assuming getReasons() returns a List : 假设getReasons()返回一个List

details.stream().
     flatMap(e -> e.getReasons().stream()).
     filter(reason -> StringUtils.equalsIgnoreCase("ABC", reason.getReasonCode())).
     forEach(System.out::println);

Where you would replace System.out::println with the method you wanted to invoke. 用您要调用的方法替换System.out::println的位置。 Also note that I removed the check of CollectionsUtil.isNotEmpty(det.getReasons()) , as if the list is empty, it won't make any difference 还要注意,我删除了CollectionsUtil.isNotEmpty(det.getReasons())的检查,就好像列表是空的一样,不会有任何区别

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

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