代碼如下:
package com.cjonline.foundation.authority.pojo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;
import com.cjonline.foundation.util.CheckNullEmpty;
/**
* 實現遞歸的幫助類,最終的結果可以描述成如下:
* 根(root)
* --1(子系統1)
* -----1.1
* -------1.1.1
* -------1.1.2
* ------- ....
* -----1.2
* --2(子系統2)
* -----2.1
* -------2.1.1
* -------2.1.2
* ------- ....
* -----2.2
*/
public class ModelList implements java.io.Serializable {
private static final Logger logger = Logger.getLogger(ModelList.class);
private static final long serialVersionUID = 6384598893693849820L;
/**
* model代表當前模塊
*/
private SysModel model;
/**
* models代表當前模塊下面的子模塊,
*/
private List<ModelList> subList = new ArrayList<ModelList>();
/**
* 菜單級別
*/
private int flag = 0;
public SysModel getModel() {
return model;
}
public void setModel(SysModel model) {
this.model = model;
}
public List<ModelList> getSubList() {
return subList;
}
public void setSubList(List<ModelList> subList) {
this.subList = subList;
}
public void setFlag(int flag) {
this.flag = flag;
}
public int getFlag() {
return flag;
}
/**
* 遞歸方法根據傳入的模塊集合形成層級菜單
*/
@SuppressWarnings("unchecked")
public ModelList createTree2(List<SysModel> ms) {
//
ModelList node = new ModelList();
ArrayList<SysModel> fu = new ArrayList<SysModel>();// 用來存儲parentId為空的父節點;
ArrayList<SysModel> childs = new ArrayList<SysModel>();// 用來存儲不是系統的模塊
// 將系統和模塊菜單分開
for (Iterator<SysModel> it = ms.iterator(); it.hasNext();) {
SysModel mode = (SysModel) it.next();
String parentId = mode.getParentId();
if (parentId == null || parentId.equals("")) {
fu.add(mode);
} else {
childs.add(mode);
}
}
//由於是多個子系統,首先要找出有多少個子系統
for (SysModel model : fu) {
ModelList node1 = new ModelList();
node1.setFlag(0);
node1.setModel(model);
node.subList.add(node1);
appendChild(node1, childs);
}
return node;
}
/**
* node節點 childs為所以系統下的子節點
*/
public void appendChild(ModelList node, List<SysModel> childs) {
if (node != null) {
String systemId = node.getModel().getSystemId();
String smid = node.getModel().getSysModuleId();
int flag = node.getFlag();
if (childs != null && childs.size() > 0) {
for (SysModel model : childs) {
String systemId2 = model.getSystemId();
String parentId2 = model.getParentId();
if (systemId.equals(systemId2)) {
if (parentId2.equals(smid)) {
ModelList child = new ModelList();
child.setModel(model);
child.setFlag(flag + 1);
node.getSubList().add(child);
appendChild(child, childs);
}
}
}
}
}
}
}