您的位置:首页 > 家用电器 > 厨房电器 > java递归树

java递归树

luyued 发布于 2011-04-12 15:03   浏览 N 次  

  首先实体类如下:

  public class Entity

  {

  private String id; private String groupName; private String pid; private boolean checkGroup; private List children;

  public Entity(String id, String groupName, String pid, boolean checkGroup) { super(); this.id = id; this.groupName = groupName; this.pid = pid; this.checkGroup = checkGroup; }

  public String getId() { return id; }

  public void setId(String id) { this.id = id; }

  public String getGroupName() { return groupName; }

  public void setGroupName(String groupName) { this.groupName = groupName; }

  public String getPid() { return pid; }

  public void setPid(String pid) { this.pid = pid; }

  public boolean isCheckGroup() { return checkGroup; }

  public void setCheckGroup(boolean checkGroup) { this.checkGroup = checkGroup; }

  public List getChildren() { return children; }

  public void setChildren(List children) { this.children = children; } } 生成树形结构的类如下:

  public class EneityUtil { public static List getResult(List src) { List parents = new ArrayList(); for(Entity ent : src) { if(ent.isCheckGroup()) { Entity result = ent; result.setChildren(new ArrayList()); parents.add(result); } } List last = new ArrayList(); for(Entity ent : src) { if(!ent.isCheckGroup()) { last.add(ent); } } buildTree(parents, last); return parents; } private static void buildTree(List parents, List others) { List record = new ArrayList(); for(Iterator it = parents.iterator(); it.hasNext();) { Entity vi = it.next(); if(vi.getId() != null) { for(Iterator otherIt = others.iterator(); otherIt.hasNext();) { Entity inVi = otherIt.next(); if(vi.getId().equals(inVi.getPid())) { if(null == vi.getChildren()) { vi.setChildren(new ArrayList()); } vi.getChildren().add(inVi); record.add(inVi); otherIt.remove(); } } } } if(others.size() == 0) { return; } else { buildTree(record, others); } } @SuppressWarnings("all") public static void main(String[] args) { List src = new ArrayList(); Entity ent0 = new Entity("0", "ALL", null, true); Entity ent1 = new Entity("1", "中国", "0" , false); Entity ent2 = new Entity("11", "YY", "1" , false); Entity ent3 = new Entity("111", "XX", "11", false); Entity ent6 = new Entity("1111", "ZZ", "111", false); Entity ent4 = new Entity("2", "美国", "0" , false); Entity ent5 = new Entity("21", "华盛顿", "2" , false); src.add(ent0); src.add(ent1); src.add(ent2); src.add(ent3); src.add(ent4); src.add(ent5); src.add(ent6); List result = getResult(src); System.out.println(result.size()); }

  }

  可以在debug中看result变量情况.

广告赞助商