/**
* 查询所有分类,按顺序显示
* 显示出树状
* @return
*/
public List<DealCategory> getCategories() {
List<DealCategory> dealCategories = getAllWithoutDeleted();//从缓存或数据库中查询全部
//JDK8的stream处理,把根分类区分出来
List<DealCategory> roots = dealCategories.stream().filter(dealCategory -> (dealCategory.getParentId() == 0)).collect(Collectors.toList());
//对跟分类进行排序
roots.sort(new Comparator<DealCategory>() {
@Override
public int compare(DealCategory o1, DealCategory o2) {
return o1.getOrderNum() > o2.getOrderNum() ? 1 : -1;
}
});
//把非根分类区分出来
List<DealCategory> subs = dealCategories.stream().filter(dealCategory -> (dealCategory.getParentId() != 0)).collect(Collectors.toList());
//递归构建结构化的分类信息
roots.forEach(root -> buildSubs(root, subs));
return roots;
}
/**
* 递归构建
* @param parent
* @param subs
*/
private void buildSubs(DealCategory parent, List<DealCategory> subs) {
List<DealCategory> children = subs.stream().filter(sub -> (sub.getParentId() == parent.getId())).collect(Collectors.toList());
if (!CollectionUtils.isEmpty(children)) {//有子分类的情况
parent.setChildren(children);
children.forEach(child -> buildSubs(child, subs));//再次递归构建
}
}
点击查看更多内容
2人点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦