栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

扁平数据根据parentID构建树形结构

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

扁平数据根据parentID构建树形结构

扁平数据根据parentID构建树形结构
package com.example.duohoob.test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;


public class TreeList {

	public static void main(String[] args) {
		
		// 模拟数据
		List> maps = new ArrayList>();
		Map m1 = new HashMap();
		m1.put("id", 1);
		m1.put("name", "a");
		m1.put("parentId", null);
		maps.add(m1);
		Map m2 = new HashMap();
		m2.put("id", 2);
		m2.put("name", "b");
		m2.put("parentId", 1);
		maps.add(m2);
		Map m3 = new HashMap();
		m3.put("id", 3);
		m3.put("name", "c");
		m3.put("parentId", null);
		maps.add(m3);
		Map m4 = new HashMap();
		m4.put("id", 4);
		m4.put("name", "d");
		m4.put("parentId", 3);
		maps.add(m4);
		Map m5 = new HashMap();
		m5.put("id", 5);
		m5.put("name", "e");
		m5.put("parentId", 4);
		maps.add(m5);
		System.out.println(JSON.toJSONString(maps));
		
		List idList = new ArrayList(maps.size());
		List> roots = new ArrayList>(); // 根节点
		Map>> children = new HashMap>>(); // 所有下级节点
		for (Map map : maps) {
			idList.add((Integer) map.get("id"));
		}
		for (Map map : maps) {
			Integer parentId = (Integer) map.get("parentId");
			if (idList.contains(parentId)) {
				children.computeIfAbsent(parentId, key -> new ArrayList>()).add(map);
				
				// 作用相当于
				
			} else {
				roots.add(map);
			}
		}
		
		// 构建树形结构
		setChildList(roots, children);
		System.out.println(JSON.toJSONString(roots));
		
	}

	private static void setChildList(List> roots, Map>> children) {
		// TODO Auto-generated method stub
		for (Map parent : roots) {
			List> childList = children.get((Integer) parent.get("id"));
			if (null != childList && childList.size() > 0) {
				parent.put("childList", childList);
				
				// 递归
				setChildList(childList, children);
			}
		}
	}
	
}

[
    {
        "name":"a",
        "childList":[
            {
                "name":"b",
                "id":2,
                "parentId":1
            }
        ],
        "id":1
    },
    {
        "name":"c",
        "childList":[
            {
                "name":"d",
                "childList":[
                    {
                        "name":"e",
                        "id":5,
                        "parentId":4
                    }
                ],
                "id":4,
                "parentId":3
            }
        ],
        "id":3
    }
]

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/344797.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号