layui树形菜单格式,java实现

springboot jpa Lombok(以空间换时间,克隆一个集合用来存剩下的节点) 

递归将平级list转换父子关系

  public Object getTreeList() {
        ArrayList treeList = menuDao.getTreeList();
        ArrayList trees = (ArrayList) treeList.clone();
        ArrayList roots= new ArrayList<>();
        for(MenuTree menuTree :treeList){
            if(menuTree.getPid().equals("0")){
                roots.add(menuTree);
                trees.remove(menuTree);
            }
        }
        treeList = convertTree(roots,trees);
        return treeList;
    }

    public ArrayList convertTree(ArrayListroots,ArrayList trees) {
        if(trees.size()==0)return roots;
        ArrayList leafs = new ArrayList<>();
        ArrayList remains = new ArrayList<>();
        remains = (ArrayList) trees.clone();
        for (MenuTree root : roots) {
            for (MenuTree leaf : trees) {
                if (root.getId().equals(leaf.getPid())) {
                    root.getChildren().add(leaf);
                    leafs.add(leaf);
                    remains.remove(leaf);
                }
            }
        }
        convertTree(leafs,remains);
        return roots;
    }

MenuTree实体

import lombok.Data;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Transient;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

@Data
@Entity
public class MenuTree implements Serializable {
    @Id
    private String id;
    private String pid;
    private String label;
    private String type;
    private String status;
    private String href;

    @Transient
    private List children = new ArrayList<>();


    public MenuTree(String id, String pid, String label) {
        this.id = id;
        this.pid = pid;
        this.label = label;
    }

}

 

 

你可能感兴趣的:(Java)