后台处理树形数据工具类

直接上工具类
要求:实体类必有字段
id
pId

package com.yibuqiche.utils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yibuqiche.user.pojo.EpcCatalog;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 处理树形数据的工具类
 */
public class TreeToolUtils {
    //把查询到的根节点放到这下面
    private List rootList;
    //把所有的非根节点方法这下面
    private List bodyList;

    public TreeToolUtils(List rootList, List bodyList) {
        this.rootList = rootList;
        this.bodyList = bodyList;
    }

    //入口程序
    public List getTree() {
        if (bodyList != null && !bodyList.isEmpty()) {
            Map map = Maps.newHashMapWithExpectedSize(bodyList.size());
            rootList.forEach(beanTree -> getChild(beanTree, map));
            return rootList;
        }
        return null;
    }

    public void getChild(EpcCatalog beanTree, Map map) {
        List childList = Lists.newArrayList();
        bodyList.stream().filter(c -> !map.containsKey(c.getId())).filter(c -> c.getpId().equals(beanTree.getId())).forEach(c -> {
            map.put(c.getId(), c.getpId());
            getChild(c, map);
            childList.add(c);
        });
        beanTree.setChildren(childList);
    }
    } 
    
    到此结束
    ------------------------------------------------------------------------
//测试数据
//    public static void main(String[] args) {
//        EpcCatalog beanTree1 = new EpcCatalog();
//        beanTree1.setCode("540000");
//        beanTree1.setLabel("西藏省");
//        beanTree1.setpId("100000");
//        EpcCatalog beanTree2 = new EpcCatalog();
//        beanTree2.setCode("540100");
//        beanTree2.setLabel("拉萨市");
//        beanTree2.setPid("540000");
//        EpcCatalog beanTree3 = new EpcCatalog();
//        beanTree3.setCode("540300");
//        beanTree3.setLabel("昌都市");
//        beanTree3.setPid("540000");
//        EpcCatalog beanTree4 = new EpcCatalog();
//        beanTree4.setCode("540121");
//        beanTree4.setLabel("林周县");
//        beanTree4.setPid("540100");
//        EpcCatalog beanTree5 = new EpcCatalog();
//        beanTree5.setCode("540121206");
//        beanTree5.setLabel("阿朗乡");
//        beanTree5.setPid("540121");
//        EpcCatalog beanTree6 = new EpcCatalog();
//        List rootList = new ArrayList<>();
//        rootList.add(beanTree1);
//        List bodyList = new ArrayList<>();
//        bodyList.add(beanTree1);
//        bodyList.add(beanTree2);
//        bodyList.add(beanTree3);
//        bodyList.add(beanTree4);
//        bodyList.add(beanTree5);
//        TreeToolUtils utils = new TreeToolUtils(rootList, bodyList);
//        List result = utils.getTree();
//        result.get(0);
//    }

你可能感兴趣的:(后台处理树形数据工具类)