定义树形结构接口
import java.util.List;
public interface BaseTree<T> {
String getId();
void setId(String id);
String getPid();
void setPid(String pid);
List<T> getChildren();
void setChildren(List<T> children);
}
模板方法+泛型进行封装的树形结构工具类
package com.zm.decorator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public abstract class TreeUtil<T extends BaseTree<T>, N> {
protected abstract N getId(T t);
protected abstract N getPid(T t);
public List<T> parseTree(List<T> list) {
if(list.isEmpty()){
return list;
}
List<T> resultList = new ArrayList<>();
Map<N, T> tmpMap = new HashMap<>(list.size());
for (T t : list) {
tmpMap.put(this.getId(t), t);
}
for (T t : list) {
T tmap = tmpMap.get(this.getPid(t));
if (tmap != null) {
if (null == tmap.getChildren()) {
tmap.setChildren(new ArrayList<>());
}
tmap.getChildren().add(t);
} else {
resultList.add(t);
}
}
list.clear();
list = null;
return resultList;
}
}
使用
import java.util.List;
public class TestNode implements BaseTree<TestNode>{
private List<TestNode> children;
private String id;
private String pid;
private String name;
@Override
public List<TestNode> getChildren() {
return children;
}
@Override
public void setChildren(List<TestNode> children) {
this.children = children;
}
@Override
public String getId() {
return id;
}
@Override
public void setId(String id) {
this.id = id;
}
@Override
public String getPid() {
return pid;
}
@Override
public void setPid(String pid) {
this.pid = pid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public static void main(String[] args) {
ArrayList<TestNode> objects = getTestNodes();
test1(objects);
}
private static void test1(ArrayList<TestNode> objects) {
TreeUtil<TestNode, String> treeUtil = new TreeUtil<TestNode, String>() {
@Override
protected String getId(TestNode e) {
return e.getId();
}
@Override
protected String getPid(TestNode e) {
return e.getPid();
}
};
List<TestNode> testNodes = treeUtil.parseTree(objects);
System.out.println(testNodes);
}
private static ArrayList<TestNode> getTestNodes() {
TestNode testNode1 = new TestNode();
testNode1.setName("中国");
testNode1.setId("0");
TestNode testNode2 = new TestNode();
testNode2.setName("福建省");
testNode2.setId("1");
testNode2.setPid("0");
TestNode testNode3 = new TestNode();
testNode3.setName("浙江省");
testNode3.setId("2");
testNode3.setPid("0");
TestNode testNode4 = new TestNode();
testNode4.setName("福州市");
testNode4.setId("3");
testNode4.setPid("1");
TestNode testNode5 = new TestNode();
testNode5.setName("宁德市");
testNode5.setId("4");
testNode5.setPid("1");
ArrayList<TestNode> objects = new ArrayList<>();
objects.add(testNode1);
objects.add(testNode2);
objects.add(testNode3);
objects.add(testNode4);
objects.add(testNode5);
return objects;
}
|