我们要用到树形菜单的时候需要一些工具类,但是菜单显示的内容或者字段个数不一样,要统一封装,直接上代码
package common;
import org.apache.commons.lang.StringUtils;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* * 类名称:MenuTreeUtil
* * 类描述:递归构造树型结构
*
*/
public class MenuTreeUtil {
public static Map<String, Object> mapArray = new LinkedHashMap<String, Object>();
public List<Map<String,Object>> menuCommon;
public List<Object> list = new ArrayList<Object>();
/***
*
* @param menuList
* @param ids 主键 {"显示的字段","数据库查询出来的字段"}
* @param parentIds 父键{"显示的字段","数据库查询出来的字段"}
* @param names 名称{"显示的字段","数据库查询出来的字段"}
* @param children 子集 key 例如: sub
* @param params 其它参数列表 {"显示的字段","数据库查询出来的字段"}
* @return
*/
public List<Object> menuList(List<Map<String,Object>> menuList,String[] ids,String[] parentIds,String[] names,String children,String[]... params) {
if(menuList ==null){
menuList=new ArrayList<Map<String,Object>>();
}
this.menuCommon = menuList;
for (Map<String,Object> x : menuList) {
Map<String, Object> mapArr = new LinkedHashMap<String, Object>();
String s=x.get(parentIds[1]).toString();
System.out.println("_________________________________________________________________________________"+s);
if ("0".equals(s)) {
mapArr.put(ids[0], x.get(ids[1]));
mapArr.put(parentIds[0], x.get(parentIds[1]));
mapArr.put(names[0], x.get(names[1]));
if(null != params){
for (int i=0;i<params.length;i++){
String [] tempArray=params[i];
mapArr.put(tempArray[0],x.get(tempArray[1]));
}
}
mapArr.put(children, menuChild(obj2Str(x.get(ids[1])),ids,parentIds,names,children,params));
list.add(mapArr);
}
}
return list;
}
/***
*
* @param id
* @param ids
* @param parentIds
* @param names
* @param children
* @param params
* @return
*/
private List<?> menuChild(String id,String[] ids,String[] parentIds,String[] names,String children,String[]... params) {
List<Object> lists = new ArrayList<Object>();
for (Map<String,Object> a : menuCommon) {
Map<String, Object> childArray = new LinkedHashMap<String, Object>();
if (id.equals(obj2Str(a.get(parentIds[1])))) {
childArray.put(ids[0], a.get(ids[1]));
childArray.put(parentIds[0], a.get(parentIds[1]));
childArray.put(names[0],a.get(names[1]));
if(null != params){
for (int i=0;i<params.length;i++){
String [] tempArray=params[i];
childArray.put(tempArray[0],a.get(tempArray[1]));
}
}
childArray.put(children, menuChild(obj2Str(a.get(ids[1])),ids,parentIds,names,children,params));
lists.add(childArray);
}
}
return lists;
}
private static String obj2Str(Object obj) {
if(obj == null ){
return "";
}else{
return obj.toString();
}
}
}
来源:CSDN
作者:代号793
链接:https://blog.csdn.net/u011267841/article/details/104795180