关于怎么样将List数据封装成树状结构,在网上非常多的文章,我自己也写了一个小方法,在这里做下笔记,方便自己以后查看。
package com.su.mybatis.mysql.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
public class Test {
public static void main(String[] args) throws Exception {
List<Map<String,Object>> list = new ArrayList<>();
Map<String,Object> firstMap = new HashMap<>();
firstMap.put("id", "1");
firstMap.put("text", "A");
firstMap.put("parentId", "0");
Map<String,Object> secondMap1 = new HashMap<>();
secondMap1.put("id", "21");
secondMap1.put("text", "B1");
secondMap1.put("parentId", "1");
Map<String,Object> secondMap2 = new HashMap<>();
secondMap2.put("id", "22");
secondMap2.put("text", "B2");
secondMap2.put("parentId", "1");
Map<String,Object> thirdMap1 = new HashMap<>();
thirdMap1.put("id", "31");
thirdMap1.put("text", "C1");
thirdMap1.put("parentId", "21");
Map<String,Object> thirdMap2 = new HashMap<>();
thirdMap2.put("id", "32");
thirdMap2.put("text", "C2");
thirdMap2.put("parentId", "21");
Map<String,Object> thirdMap3 = new HashMap<>();
thirdMap3.put("id", "33");
thirdMap3.put("text", "C3");
thirdMap3.put("parentId", "22");
list.add(firstMap);
list.add(secondMap1);
list.add(secondMap2);
list.add(thirdMap1);
list.add(thirdMap2);
list.add(thirdMap3);
System.out.println("list : " + JSON.toJSONString(list));
List<Map<String,Object>> resultList = encapsulateList(list, "0");
System.out.println("resultList : " + JSON.toJSONString(resultList));
}
public static List<Map<String,Object>> encapsulateList(List<Map<String,Object>> paramList, String parentId) {
List<Map<String,Object>> resultList = new ArrayList<>();
for (Map<String,Object> map : paramList ) {
String pid = map.get("parentId") == null ? "" : map.get("parentId").toString();
if( parentId.equals(pid)){
Map<String, Object> childNode = new HashMap<String, Object>();
childNode.put("id", map.get("id"));
childNode.put("text", map.get("text"));
childNode.put("children", encapsulateList(paramList, map.get("id").toString()));
resultList.add(childNode);
}
}
//如果children节点下没有数据需要把children节点删除则使用这句返回;否则,直接返回resultList
return JSONObject.parseObject(JSON.toJSONString(resultList).replace(",\"children\":[]", ""), new TypeReference<List<Map<String, Object>>>(){});
}
}
在上面用到了alibaba的fastjson工具类里面的方法,JSONObject.parseObject(obj.toJSONString(), new TypeReference<T>(){});
其中T为List<Map<String, Object>>。
如果有写的不对的地方,请大家多多批评指正,非常感谢!