需求
- 最近在做一个导出数据生成树节点的工作 ,从数据库中导出全国省市区街道数据,查询出来是 list集合需要转换成树 tree
表
CREATE TABLE dic (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(63) NOT NULL,
parent_id int(11) NOT NULL,
) ;
代码
DicTree类
import java.util.ArrayList;
import java.util.List;
public class DicTree {
private int id;
private String name;
private int parentId;
private List<DicTree> child = new ArrayList();
private int node;
public DicTree(){
}
public DicTree(int id, String name, int parentId) {
this.id = id;
this.name = name;
this.parentId = parentId;
}
}
运行代码
@Test
public void test3() {
List<DicTree> dicList = dicDao.getDicData();
List<DicTree> rootTrees = new ArrayList<DicTree>();
for (DicTree dicTree : dicList) {
if (dicTree.getParentId() == 0) {
rootTrees.add(dicTree);
}
for (DicTree childrenDicTree : dicList) {
/**
* 这里只要三级节点,如果不限制子节点个数,去掉 dicTree.getNode()判断
*/
if (dicTree.getId() == childrenDicTree.getParentId() && dicTree.getNode() < 2) {
if (dicTree.getChild() == null || dicTree.getChild().size() == 0) {
List<DicTree> myChildrens = new ArrayList<DicTree>();
myChildrens.add(childrenDicTree);
dicTree.setChild(myChildrens);
} else {
dicTree.getChild().add(childrenDicTree);
}
}
}
}
System.out.println("开始写出文件.......");
try {
File file = new File("/mnt/dic/dic10028.json");
PrintStream ps = new PrintStream(new FileOutputStream(file));
/**
* 防止 fastjson把对象转化成json出现 $ref,加上 SerializerFeature.DisableCircularReferenceDetect
*/
ps.println(JSON.toJSONString(rootTrees, SerializerFeature.DisableCircularReferenceDetect));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println("写出完毕.......");
}
优化版
public static void main(String[] args) {
List<DicTree> dicList = new ArrayList<>();
dicList.add(new DicTree(1, "测试1", 0));
dicList.add(new DicTree(2, "测试2", 1));
dicList.add(new DicTree(3, "测试3", 2));
dicList.add(new DicTree(4, "测试4", 0));
List<DicTree> dicTrees = test3(dicList);
System.out.println(dicTrees.toString());
}
public static List<DicTree> test3(List<DicTree> dicList) {
if (dicList.size() == 1) {
return dicList;
}
List<Integer> removeList = new ArrayList<>();
for (DicTree dicTree : dicList) {
for (DicTree childrenDicTree : dicList) {
if (dicTree.getId() == childrenDicTree.getParentId() && dicTree.getNode() < 2) {
if (dicTree.getChild() == null || dicTree.getChild().size() == 0) {
List<DicTree> myChildrens = new ArrayList<>();
removeList.add(childrenDicTree.getId());
myChildrens.add(childrenDicTree);
dicTree.setChild(myChildrens);
} else {
removeList.add(childrenDicTree.getId());
dicTree.getChild().add(childrenDicTree);
}
}
}
}
for (int i = 0; i < dicList.size(); i++) {
DicTree item = dicList.get(i);
if (removeList.contains(item.getId())) {
dicList.remove(item);
i--;
}
}
return dicList;
}