user10382836
user10382836

Reputation: 87

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
                        }
                    }

                    }
                }
            }

Upvotes: 0

Views: 5419

Answers (1)

GBlodgett
GBlodgett

Reputation: 12819

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

Upvotes: 3

Related Questions