无限极分类JAVA 实现 Tree

无限极分类JAVA 实现 Tree_第1张图片 

工具类: 


import java.lang.reflect.Field;
import java.util.*;

public class MenuVueTreeUtil {

    private List list = new ArrayList<>();
    public String asId = "id";
    public String asPid = "pid";
    public String asChild = "children";
    public List> WashAfterData = new ArrayList<>();  //洗刷后数据



    //格式化数据
    public MenuVueTreeUtil format(List menu) throws IllegalAccessException {
        for (Object x : menu) {
            Class clazz = x.getClass(); //每行数据
            Map _ar = new HashMap<>();
            for (Field field : clazz.getDeclaredFields()) {
                field.setAccessible(true);
                String fieldName = field.getName().replace("$cglib_prop_", ""); //动态类
                _ar.put(fieldName, field.get(x));
            }
            if (!_ar.isEmpty()) {
                WashAfterData.add(_ar);
            }
        }
        return this;
    }

    //获取子孙树菜单
    public List menu() {
        for (int i = 0; i < WashAfterData.size(); i++) {
            Map mapArr = new LinkedHashMap<>();
            if (WashAfterData.get(i).get(this.asPid).toString().equals("0")) {
                WashAfterData.get(i).forEach((k, v) -> {
                    mapArr.put(k, v);
                });
                mapArr.put(this.asChild, this.child(WashAfterData.get(i).get(this.asId).toString()));
                list.add(mapArr);
            }
        }
        return list;
    }

    private List child(String id) {
        List lists = new ArrayList<>();
        for (int i = 0; i < WashAfterData.size(); i++) { //全部数据
            Map mapArr = new LinkedHashMap<>();
            if (WashAfterData.get(i).get(this.asPid).toString().equals(id)) {
                WashAfterData.get(i).forEach((k, v) -> {
                    mapArr.put(k, v);
                });
                mapArr.put(this.asChild, this.child(WashAfterData.get(i).get(this.asId).toString()));
                lists.add(mapArr);
            }
        }
        return lists;
    }
} 
  

使用实例: 

 List data    = "数据库查询 菜单";

 List menuTree = menuVueTreeUtil.format(data).menu(); 
  

 

你可能感兴趣的:(工具)