Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java use streams to modify nested list and return parent list

I have following dto

public class StepsDto {
    
    private String step;
    private String status;
    private List<StepsDto> sub_steps;
    private String previousStep;
    private String nextStep;
}

Using streams I need to change the status of Substeps if name of a particular step and its substep and its sub sub step matches.
And then I need to return the complete Parent list of Steps.

I have tried using flatmap but it returns sublist and not the main list.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So for example I have parent step P1,child step C1 and in the child I have another child CC1. I want to change the status of CC1 and return the Parent list.

>Solution :

You are not specifying what kind of stream usage you are looking for. You don’t need flatMap because you are not going to update the structure of the list but only modify the values in it.

You can forcibly use the stream() to iterate over your lists and update the values in place.

    List<StepsDto> l1steps = new ArrayList<>();

    l1steps.stream().forEach(l1step -> {
        l1step.sub_steps.stream().forEach(l2step -> {
            l2step.sub_steps.stream().forEach(l3step -> {
                if(l3step.step.equals(l2step.step) && l3step.step.equals(l1step.step)){
                    l3step.status = "newStatus";
                }
            });
        });
    });

Alternatively, if you don’t want to modify the values in place, instead of foreach you could use map while creating new instances of steps each time.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading