1. 程式人生 > >後臺處理樹形資料工具類

後臺處理樹形資料工具類

直接上工具類
要求:實體類必有欄位
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<EpcCatalog> rootList;
    //把所有的非根節點方法這下面
    private List<EpcCatalog> bodyList;

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

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

    public void getChild(EpcCatalog beanTree, Map<String, String> map) {
        List<EpcCatalog> 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<EpcCatalog> rootList = new ArrayList<>();
//        rootList.add(beanTree1);
//        List<EpcCatalog> 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<EpcCatalog> result = utils.getTree();
//        result.get(0);
//    }