拆分字符串为树形结构

package test;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
/**
*拆分目录结构,这里拆分用小数点代替。
*
*/
public class RenameFile { public static void main(String[] args) throws IOException { List<String> rootStrs = new ArrayList<String>(); rootStrs.add("c.a.b.c"); rootStrs.add("d.a.b.c"); rootStrs.add("c.a.c.c"); rootStrs.add("c.b.b.c.1"); Dir root = new Dir("root"); for(String rootStr : rootStrs){ List<Dir> eachList = null; for(String str: rootStr.split("\\.")){ if(eachList == null){ eachList = root.getChild(); } eachList = creatChild(str,eachList); } } } private static List<Dir> creatChild(String str,List<Dir> child){ //如果已经存在 for(Dir dirEle:child){ if(dirEle.getName().equals(str)){ return dirEle.getChild(); } } Dir dir = new Dir(str); child.add(dir); return dir.getChild(); } } class Dir{ String name; List<Dir> child = new ArrayList<Dir>(); Dir(String name){ this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Dir> getChild() { return child; } public void setChild(List<Dir> child) { this.child = child; } }

 

posted @ 2017-10-11 15:48  剑神西门吹雪  阅读(778)  评论(0编辑  收藏  举报