I have a class called Item
, and it's defined as following :
public class Item {
private Long id;
private String text;
}
And it's DTO is as following :
public class ItemDTO {
private String id;
private String text;
private List<ItemDTO> children;
}
So using a DAO function I will retrieve an object children using it's id
from database, as following :
List<Item> children = itemDAO.findChildrenForItem(id);
And for each child I will retrieve it's children and so on..., for that I created a recursive function, which worked in this case :
public List<ItemDTO> process(Long id) {
List<ItemDTO> list = new ArrayList<>();
// Get children
List<Item> children = itemDAO.findChildrenForItem(id);
if (children != null && children.size() > 0) {
for (Item child : children) {
ItemDTO dto = new ItemDTO();
dto.setId(String.valueOf(child.getId()));
dto.setText(child.getLib());
dto.setChildren(process(child.getId()));
list.add(dto);
}
}
return list;
}
Here what I want to do is that when I reach the 5th iteration in the recursive method to stop and move to the next element in the children
array.
So the first level children will have 4 level children, and the second level children will have 3 level children and so on..., so this is what I tried :
public List<ItemDTO> process(Long id, Integer level) {
List<ItemDTO> list = new ArrayList<>();
// Get children
List<Item> children = itemDAO.findChildrenForItem(id);
if (children != null && children.size() > 0) {
for (Item child : children) {
level = level != null ? level : 0;
ItemDTO dto = new ItemDTO();
dto.setId(String.valueOf(child.getId()));
dto.setText(child.getLib());
level++;
dto.setChildren(level <= 4 ? process(child.getId(), level) : null);
list.add(dto);
level = 0;
}
}
return list;
}
But this didn't work I always get children more than the forth level.
How can I solve this ?