简体   繁体   中英

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. 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. Below is sample way in java 7 not the best approach thou.

 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 :

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. Also note that I removed the check of CollectionsUtil.isNotEmpty(det.getReasons()) , as if the list is empty, it won't make any difference

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