代码
@Override
public ServerResponse getSelfAndChildrenCategory(Integer categoryId) {
if (categoryId != null) return ServerResponse.error(ResponseCode.ILLEGAL_ARGUMENT.getCode(), "参数错误");
Set<Category> categorySet = Sets.newHashSet(); // 初始化Set
findChildCategory(categorySet, categoryId); // 递归
List<Integer> categoryIdList = Lists.newArrayList(); // 初始化List
for (Category categoryItem : categorySet) {
categoryIdList.add(categoryItem.getId());
}
return ServerResponse.success(categoryIdList);
}
//递归算法,算出子节点
private Set<Category> findChildCategory(Set<Category> categorySet, Integer categoryId) {
Category category = categoryMapper.selectByPrimaryKey(categoryId);
// 将自己添加进去
if (category != null) categorySet.add(category);
//查找子节点,递归算法一定要有一个退出的条件
List<Category> categoryList = categoryMapper.getChildrenCategory(categoryId);
for (Category categoryItem : categoryList) {
findChildCategory(categorySet, categoryItem.getId());
}
return categorySet;
}
/** 重写id的equals和hashCode方法,保证Set集合取出的值是不重复的 */
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Category category = (Category) o;
return id.equals(category.id);
}
@Override
public int hashCode() {
return id.hashCode();
}
参考文章