JavaList集合递归树状结构

2022-07-30 11:16:32

从数据库查出一堆集合数据之后,数据是按照一二三级这种规律,在这里做一个树状排序,为了方便大家优化了下代码,直接复制粘贴就可以使用

数据需要id,pid,name即可支持

首先引入net.sf.JSON,个人比较习惯用这个,读者随意

/**
 *parentId为当前List最上层父id
 *idKey为实体类对象中id键名
 *parentKey为实体类对象中id的键名
 *childName为返回数据子列表的命名
 */
public class treeObjectList{
    publlic static JSONArray forObjectToTreeMap(List<?> treeList,Long parentId,String idKey,String parentIdKey,String childName){
        JSONArray childMenu = new JSONArray();
        for(Object object : treeList){
            JSONObject jsonMenu = JSONObject.fromObject(object);
            Long menuId = jsonMenu.getLong(idKey); 
            Long pid = jsonMenu.getLong(parentIdKey);
            if(parentId==pid){
                JSONArray array = forObjectToTreeMap(treeList,menuId);
                jsonMenu.put(childName,array);
                childMenu.add(jsonMenu);
            }
        }
        return childMenu;
    }
}

调用:

//假设最上级父ID为0
List<menu> menuList = new ArrayList<>();
JSONArray menuarray = treeObjectList.forObjectToTreeMap(menuList,(long)0,"id","parentId","childList");
return menuarray;
  • 作者:余额一个亿
  • 原文链接:https://blog.csdn.net/MengDiL_yl/article/details/89092799
    更新时间:2022-07-30 11:16:32