我想它能帮上你,看你的模型应该是将平级的对象转换成树型对象。我这个项目中有树是以pid来维护的,但后台是用extjs写的,有时为了extjs的树的展现,需要将list转换成树的数据结构。下面这个类就是做这个处理的。它将任意一个带上下级关系的List集合转换成最后的树型结果。
package com.lenxeon.extjs.core.utils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import java.util.*;
public class Convert {
public static Collection List2Tree(Collection list, String pidKey, String childrensKey) {
return conver(list, pidKey, childrensKey);
}
private static Collection conver(Collection list, String pidKey, String childrensKey) {
Collection root = new ArrayList();
for (Map menu : list) {
if (MapUtils.getIntValue(menu, pidKey, -1) == 0) {
root.add(menu);
}
}
list.removeAll(root);
mapping(list, root, pidKey, childrensKey);
return root;
}
private static void mapping(Collection source, Collection list, String pidKey, String childrensKey) {
for (Map menu : list) {
Set root = new LinkedHashSet();
for (Map s : source) {
if (MapUtils.getIntValue(s, pidKey, -1) == MapUtils.getIntValue(menu, "id", -2)) {
root.add(s);
}
}
menu.put(childrensKey, root);
if (root.size() > 0) {
menu.put("leaf", false);
} else {
menu.put("leaf", true);
}
source.removeAll(root);
mapping(source, (Collection) MapUtils.getObject(menu, childrensKey), pidKey, childrensKey);
}
}
public static List copyKey(List list, String[] form, String[] to) {
if (list == null) {
list = new ArrayList();
}
if (form == null || to == null || form.length != to.length) {
return list;
}
for (Map m : list) {
for (int i = 0; i < form.length; i++) {
String f = form[i];
String t = to[i];
if (StringUtils.isNotBlank(f) && StringUtils.isNotBlank(t)) {
m.put(t, MapUtils.getObject(m, f));
}
}
}
return list;
}
}