数组转树形结构只需两步
大约 1 分钟
已很经典的菜单为例,假设结构如下:
- id
- parent_id
- name
- xxx1
- xxx2
- ….
按照一比一构造一个类(只增加一个children字段):
@Data
public class XXXX{
private Long id;
private Long parentId;
private String name;
private String xxx1;
private String xxx2;
private List<XXXX> children;
}
public List<XXXX> treeMenu() {
List<XXXX> xxxxs = xxxxDao.menuList();
//第一步分组
Map<Long, List<XXXX>> parentId2Children =
xxxxs.stream().collect(Collectors.groupingBy(i -> i.getParentId()));
//第二步构造树
List<XXXX> roots = parentId2Children.remove(0L);
buildTree(roots, parentId2Children);
return roots;
}
private void buildTree(List<XXXX> parents,
Map<Long, List<XXXX>> parentId2Children) {
if (CollUtil.isEmpty(parents)) {
return;
}
parents.sort(Comparator.comparing(XXXX::getId));
for (XXXX parent : parents) {
List<XXXX> children = parentId2Children.remove(parent.getId());
parent.setChildren(children);
buildTree(children, parentId2Children);
}
}
系统推荐
- Cordova+Umi项目搭建步骤
- MongoDB高可用
- Spring RetryTemplate
- ShadowsockServer
- MySQL锁、事务、隔离级别
- InnoDB存储引擎
- 制作KVM ES镜像文件
- Javassist整理
- CountDownLatch源码解读
- SpringCloud总体认识
- intro
- 杂记
- 随机毒鸡汤:月老麻烦下次为我牵红线,能换成钢丝吗?红线老TM断。