package testng;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
public class Test {
/**
* 添加节点
* @param nodeMap
* @param parentNodeName 父节点名称
* @param nodeName
*/
public static void addNode(Map nodeMap,String parentNodeName,String nodeName){
Node parentNode = null != parentNodeName ? nodeMap.get(parentNodeName) : null;
Node node = nodeMap.get(nodeName);
if(null != node){
return;
}
node = new Node();
node.setName(nodeName);
nodeMap.put(nodeName, node);
if(null != parentNode){
parentNode.addChild(node);
node.setParent(parentNode);
}
}
public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
String [] arrays = new String[]{
"测试/测试1/测试2",
"工单/问题反馈309",
"工单/问题反馈565",
"工单/问题反馈54",
"工单/问题反馈310",
"测试专用/123456/test/123"
};
Map resultMap = new HashMap();
for(String line : arrays){
String nodeNameArray [] = line.split("/");
String preNodeName = null;
for(String curNodeName : nodeNameArray){
addNode(resultMap,preNodeName,curNodeName);
preNodeName = curNodeName;
}
}
for(Map.Entry entry : resultMap.entrySet()){
Node node = entry.getValue();
if(null == node.getParent()){
print(node,"");
}
}
}
/**
* 递归打印node
* @param node
* @param blank
*/
public static void print(Node node,String blank){
System.out.println(blank + node.getName());
if(node.getChilds() == null || node.getChilds().isEmpty()){
return;
}
for(Node cur : node.getChilds()){
print(cur,blank + " ");
}
}
static class Node{
private String name;
private int index;
private List childs;
private Node parent;
public List getChilds() {
return childs;
}
public void addChild(Node child) {
if(null == childs){
childs = new ArrayList();
}
childs.add(child);
}
public Node getParent() {
return parent;
}
public void setParent(Node parent) {
this.parent = parent;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}
}
打印结果:
测试
测试1
测试2
测试专用
123456
test
123
工单
问题反馈309
问题反馈565
问题反馈54
问题反馈310