遞迴這樣理解,你將豁然開朗;
方法1:無返回值法
@GetMapping("/index6")
public List<Integer> index6() {
Integer id = 11;
List<Category> categoryList = categoryMapper.selectList(null);
// 宣告引用返回值
List<Integer> result = new ArrayList<>();
checkCateData(categoryList, id, result);
return result;
}
/**
*
* @param list 分類列表
* @param id 查詢id
* @param result 蒐集返回值(子分類所有id)
* @return
*/
private void checkCateData(List<Category> list, Integer id,List<Integer> result) {
for (Category ca : list
) {
if (ca.getFatherId().equals(id)){
Integer ids = ca.getId();
result.add(ids);
checkCateData(list,ids,result);
}
}
}
方法2:有返回值
/**
* 有返回值接收
* @param categoryList
* @param id
* @return
*/
private List<CategoryTreeVO> deepCategoryDataList(List<Category> categoryList, Integer id) {
List<CategoryTreeVO> result = new ArrayList<>();
for (Category cate : categoryList
) {
if (cate.getFatherId().equals(id)) {
CategoryTreeVO vo = new CategoryTreeVO();
vo.setName(cate.getName());
vo.setId(cate.getId());
vo.setType(cate.getType());
vo.setFatherId(cate.getFatherId());
List<CategoryTreeVO> childList = deepCategoryDataList(categoryList, cate.getId());
vo.setNodeCategoryList(childList);
result.add(vo);
}
}
return result;
}
方法3:
/**
* 透過子集查詢父級節點
* @param list
* @param parentId
* @return
*/
private List<Integer> queryFatherItem(List<Category> list, Integer parentId) {
List<Integer> result = new ArrayList<>();
for (Category cate : list
) {
if (cate.getId().equals(parentId)) {
result.add(cate.getId());
List<Integer> integers = queryFatherItem(list, cate.getFatherId());
result.addAll(integers);
}
}
return result;
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結