将树形结构转换行
package com.qingyu.controller;
import java.util.*;
/**
* @author xiaoliu
* @Date 2024-07-31 22:38
**/
public class testDemo {
public static void main(String[] args) {
List<Map<String, Object>> tangzhenchildren = new ArrayList<>();
Map<String, Object> yulan1 = new HashMap();
yulan1.put("id", "yulan1");
yulan1.put("label", "玉兰一");
Map<String, Object> yulan2 = new HashMap();
yulan2.put("id", "yulan2");
yulan2.put("label", "玉兰二");
tangzhenchildren.add(yulan1);
tangzhenchildren.add(yulan2);
List<Map<String, Object>> pudongchildren = new ArrayList<>();
Map<String, Object> tangzhen = new HashMap();
tangzhen.put("id", "tangzhen");
tangzhen.put("label", "唐镇");
tangzhen.put("children", tangzhenchildren);
Map<String, Object> zhangjinag = new HashMap();
zhangjinag.put("id", "zhangjinag");
zhangjinag.put("label", "张江");
pudongchildren.add(tangzhen);
pudongchildren.add(zhangjinag);
Map<String, Object> pudong = new HashMap();
pudong.put("id", "pudong");
pudong.put("label", "浦东新区");
pudong.put("children", pudongchildren);
List<Map<String, Object>> xuhuichildren = new ArrayList<>();
Map<String, Object> huajingzhen = new HashMap();
huajingzhen.put("id", "huajingzhen");
huajingzhen.put("label", "华泾镇");
xuhuichildren.add(huajingzhen);
Map<String, Object> xuhui = new HashMap();
xuhui.put("id", "xuhui");
xuhui.put("label", "徐汇区");
xuhui.put("children", xuhuichildren);
List<Map<String, Object>> shanghaigchildren = new ArrayList<>();
shanghaigchildren.add(pudong);
shanghaigchildren.add(xuhui);
Map<String, Object> shanghai = new HashMap();
shanghai.put("id", "shanghai");
shanghai.put("label", "上海");
shanghai.put("children", shanghaigchildren);
List<List<String>> lists =new ArrayList<>();
List<String> list= new ArrayList<>();
// 将数据转化成一行行的数据
List<List<String>> resultList = treeToList2(shanghai, lists, list);
List<Integer> dee = new ArrayList<>();
for (List<String> strings : resultList) {
dee.add(strings.size());
}
// 获取map的深度
int deep = Collections.max(dee);
for (int i = 0; i < resultList.size(); i++) {
// 内部的list集合
List<String> list1 = resultList.get(i);
int size = list1.size();
if (list1.size() < deep) {
// 补齐list
int i1 = deep - list1.size();
for (int j = 0; j < i1; j++) {
if (size == 1) {
list1.add("");
}
else {
list1.add("");
// list1.add(list1.get(list1.size() - 1));
}
}
}
}
System.out.println(resultList);
}
public static List<List<String>> treeToList2(Map<String, Object> map, List<List<String>> list1, List<String> list2) {
//遍历递归子节点
List<Map<String, Object>> childrens = (List<Map<String, Object>>) map.get("children");
if (childrens==null||childrens.size() == 0) {
list1.add(list2);
} else {
for (Map<String, Object> children : childrens) {
String label = children.get("label").toString();
String id = children.get("id").toString();
List<String> strings = new ArrayList<>(list2);
strings.add(label);
treeToList2(children, list1, strings);
}
}
return list1;
}
}
输出
[[浦东新区, 唐镇, 玉兰一],
[浦东新区, 唐镇, 玉兰二],
[浦东新区, 张江, ],
[徐汇区, 华泾镇, ]]