数组转树形结构只需两步

Rocky树形结构大约 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);
    }
}

系统推荐









  • 随机毒鸡汤:熬夜是年轻人的权利,头发就是资本。