数组转树形结构只需两步
已很经典的菜单为例,假设结构如下:
- 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);
}
}
系统推荐
- MyBatis
- ES6.2.3(3节点)数据迁移到ES7.4.1(5节点)
- 随记
- MongoDB高可用
- Thread & ExecutorService & ThreadPoolExecutor 总览
- 乱七八糟的笔记
- Cornell Notes System
- 数据同步方案
- Docker笔记
- MySQL索引
- JVM杂项
- 表单重复提交解决方案
- 随机毒鸡汤:世界很公平,比你忙的人赚的比你多,比你闲的人你赚的比他少。