'How to dynamically access multi level object Java 8

I have an API that returns a parent with its children, I need to implement that in java 8 to be able to return them as below:

A -> has B as Child, and C as Child -> C has C.1 as a sub child, and so on, The idea is we don't know the depth of the object (how many sub-sub child it got) So we need to perform a dynamic loop to access each child and sub child and set their values. I was able to set only the parent and only his one level child, but couldn't think of an idea that does what I want. Any helo would be much appreciated, thanks.

private TrainingCategoryDTO methodOne(Long companyId, Long trainingCategoryId){

    TrainingCategory trainingCategory = createTrainingCategory(companyId, trainingCategoryId);
    List<TrainingCategoryChildDTO> trainingCategoryChildDTOList = new ArrayList<>();

    if (CollectionUtils.isNotEmpty(trainingCategory.getChildrenIds())) {
        trainingCategory.getChildrenIds().forEach(childId -> {
            TrainingCategory childTrainingCategory = createTrainingCategory(companyId, childId);


            TrainingCategoryChildDTO trainingCategoryChildDTO =  converterService.convert(childTrainingCategory, TrainingCategory.class, TrainingCategoryChildDTO.class);
            trainingCategoryChildDTOList.add(trainingCategoryChildDTO);
        });
    }

    TrainingCategoryDTO trainingCategoryDTO = converterService.convert(trainingCategory, TrainingCategory.class, TrainingCategoryDTO.class);
    trainingCategoryDTO.setChildren(trainingCategoryChildDTOList);

    return trainingCategoryDTO;
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source