@Data
class Node extends BaseNode<String, Node> {
private String c ;
}
import java.util.List;
class BaseNode<K, T> {
K id;
K pid;
List<T> children;
public K getId() {
return id;
}
public void setId(K id) {
this.id = id;
}
public K getPid() {
return pid;
}
public void setPid(K pid) {
this.pid = pid;
}
public List<T> getChildren() {
return children;
}
public void setChildren(List<T> children) {
this.children = children;
}
}
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import java.util.List;
import java.util.Map;
public class TreeToolUtils<T extends BaseNode> {
private List<T> rootList; //根节点对象存放到这里
private List<T> bodyList; //其他节点存放到这里,可以包含根节点
public TreeToolUtils(List<T> rootList, List<T> bodyList) {
this.rootList = rootList;
this.bodyList = bodyList;
}
public List<T> getTree(){ //调用的方法入口
if(bodyList != null && !bodyList.isEmpty()){
//声明一个map,用来过滤已操作过的数据
Map<Object,Object> map = Maps.newHashMapWithExpectedSize(bodyList.size());
rootList.forEach(beanTree -> getChild(beanTree,map));
return rootList;
}
return rootList;
}
public void getChild(T beanTree,Map<Object,Object> map){
List<T> childList = Lists.newArrayList();
bodyList.stream()
.filter(c -> !map.containsKey(c.getId()))
.filter(c ->c.getPid().equals(beanTree.getId()))
.forEach(c ->{
map.put(c.getId(),c.getPid());
getChild(c,map);
childList.add(c);
});
beanTree.setChildren(childList);
}
public static void main(String[] args) {
Node node = new Node();
node.setId("1");
node.setPid("1");
node.setC("fasdA");
Node b = new Node();
b.setId("2");
b.setPid("1");
b.setC("fasdB");
Node c = new Node();
c.setId("3");
c.setPid("1");
c.setC("fasdC");
List<Node> root = Lists.newArrayList(node);
List<Node> body = Lists.newArrayList(b,c);
TreeToolUtils<Node> treeToolUtils = new TreeToolUtils<>(root,body);
List<Node> tree = treeToolUtils.getTree();
System.err.println(tree);
System.err.println(JSONObject.toJSONString(tree));
}
}
测试结果:
[{"c":"fasdA","children":[{"c":"fasdB","children":[],"id":"2","pid":"1"},{"c":"fasdC","children":[],"id":"3","pid":"1"}],"id":"1","pid":"1"}]