资源整合:Java List<T> 转换为树结构列表工具类

该工具开箱即用

1、实体类

import java.io.Serializable;
import java.util.List;
 
/**
 * treegrid树形表格基础对象,后续的该类型的对象均继承该对象
 *
 */
public class BaseTreeGrid implements Serializable{
     
 
	private static final long serialVersionUID = -9189631784252440402L;
	
	public String id;//节点id
	
	public String parentId;//节点父id
	
	public String iconCls = "folder";//节点样式,默认即可
	
	public Boolean leaf = true;//是否为叶子节点,true表示是叶子节点,false表示不是叶子节点
	
	public Boolean expanded = true; //是否展开,默认true,展开
	
	public List<BaseTreeGrid> children;//孩子节点
 
}

2、具体工具类

 	/**
     * 格式化list为树形list
     *
     * @param list
     * @return
     */
    public static <T extends BaseTreeGrid> List<T> formatTree(List<T> list) {
     
        List<T> nodeList = new ArrayList<T>();
        //父级节点
        for (T parentNode : list) {
     
            boolean mark = false;
            //子级节点
            for (T childNode : list) {
     
                //判断是否有子级节点
                if (parentNode.getParentId() != null && parentNode.getParentId().equals(childNode.getId())) {
     
                    mark = true;
                    if (childNode.getChildList() == null) {
     
                        childNode.setChildList(new ArrayList<>());
                    }
                    childNode.getChildList().add(parentNode);
                }
            }
            if(!mark){
     
                nodeList.add(parentNode);
            }
        }
        return nodeList;
    }

3、使用案例

public static void main(String[] args) {
     
		List<BaseTreeGrid> list = new ArrayList<BaseTreeGrid>();
		BaseTreeGrid root1 = new BaseTreeGrid();
		root1.setId("1");
		BaseTreeGrid child1 = new BaseTreeGrid();
		child1.setId("11");
		child1.setParentId("1");
		BaseTreeGrid child11 = new BaseTreeGrid();
		child11.setId("111");
		child11.setParentId("11");
		BaseTreeGrid root2 = new BaseTreeGrid();
		root2.setId("2");
		BaseTreeGrid child2 = new BaseTreeGrid();
		child2.setId("21");
		child2.setParentId("2");
		list.add(root1);
		list.add(child1);
		list.add(child11);
		list.add(root2);
		list.add(child2);
		List<BaseTreeGrid> treelist = formatTree(list, false);
		String json = JSONArray.toJSONString(treelist);
		System.out.println(json);
	}

你可能感兴趣的:(资源整合,intellij,idea,java)