简单list转化为tree结构


1
@Override 2 public List<Module> getTree() { 3 List<Module> list = moduleMapper.queryList(); 4 // List<Module> modules = makeTree(list); 5 return list; 6 } 7 8 private List<Module> makeTree(List<Module> list) { 9 List<Module> parent = new ArrayList<Module>(); 10 // get parentId = null; 11 for (Module e : list) { 12 if (e.getParent_Module() == null) { 13 e.setChildren(new ArrayList<Module>(0)); 14 parent.add(e); 15 } 16 } 17 // 删除parentId = null; 18 list.removeAll(parent); 19 20 makeChildren(parent, list); 21 22 return parent; 23 } 24 25 private void makeChildren(List<Module> parent, List<Module> children) { 26 if (children.isEmpty()) { 27 return; 28 } 29 30 List<Module> tmp = new ArrayList<Module>(); 31 for (Module c1 : parent) { 32 for (Module c2 : children) { 33 c2.setChildren(new ArrayList<Module>(0)); 34 if (c1.getId().equals(c2.getParent_Module().getId())) { 35 c1.getChildren().add(c2); 36 tmp.add(c2); 37 } 38 } 39 } 40 41 children.removeAll(tmp); 42 43 makeChildren(tmp, children); 44 }

补充po类:

package com.zktx.platform.entity.tb;

import java.util.ArrayList;
import java.util.List;

public class Module {
	private Integer id;
	private String class_name;
	private String description;
	private String name;
	private Integer priority;
	private String sn;
	private String url;
	private Integer parent_id;
	private Module parent_Module;
	private List<Module> children = new ArrayList<Module>();

	public Integer getId() {
		return id;
	}

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

	public String getClass_name() {
		return class_name;
	}

	public void setClass_name(String class_name) {
		this.class_name = class_name;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getPriority() {
		return priority;
	}

	public void setPriority(Integer priority) {
		this.priority = priority;
	}

	public String getSn() {
		return sn;
	}

	public void setSn(String sn) {
		this.sn = sn;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public Integer getParent_id() {
		return parent_id;
	}

	public void setParent_id(Integer parent_id) {
		this.parent_id = parent_id;
	}

	public Module getParent_Module() {
		return parent_Module;
	}

	public void setParent_Module(Module parent_Module) {
		this.parent_Module = parent_Module;
	}

	public List<Module> getChildren() {
		return children;
	}

	public void setChildren(List<Module> children) {
		this.children = children;
	}

}

  

posted on 2017-04-26 20:36  世界之大追梦者  阅读(570)  评论(0编辑  收藏  举报

导航