数组转树形结构只需两步
已很经典的菜单为例,假设结构如下:
- 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);
}
}
系统推荐
- Notion笔记定时备份
- JVM垃圾收集器
- Spring框架源码关键点
- 微博关注关系如何实现
- Spring Cloud(一):服务治理技术概览【Finchley 版】
- 你真的会拼接字符串吗?
- Redis高可用
- InnoDB存储引擎
- PasteImageIntoMarkdown插件开发
- Centos离线安装Docker
- JVM杂项
- Docker跨主机通信方案
- 随机毒鸡汤:你什么货色,我什么脸色。