java 組裝樹形結構

package cn.thinkjoy.kidscare.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializeFilter;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.util.CollectionUtils;

import java.util.*;


/***
 *
 * @ClassName: TreeUtils
 * @Description: 組織樹結構
 * @author liyuhang
 *
 */
public class TreeUtils {

	/****
	 *
	 * @Title: getTreeByStack
	 * @Description: 獲取樹形結構字符串
	 * @param  jsonRootList 全部根結點
	 * @return String  樹形字符串
	 */
	public static String getTreeByStack(JSONArray jsonRootList, Map<Long, JSONArray> parentMap){
		Stack<JSONObject> stack=new Stack<JSONObject>();
		for(int i=0;i<jsonRootList.size();i++){
			JSONObject root=jsonRootList.getJSONObject(i);
			stack.push(root);
		}

		while (!stack.isEmpty()) {
			JSONObject parentNode=stack.pop();
			if (!CollectionUtils.isEmpty(parentMap.get(parentNode.getLong("id")))) {
				JSONArray list = parentMap.get(parentNode.getLong("id"));
				parentNode.put("values", list);
				for(int k=0;k<list.size();k++){
					stack.push(list.getJSONObject(k));
				}
			}else{
				parentNode.put("values", new JSONArray());
			}
		}
		String tree=jsonRootList.toString();
		return tree;
	}

	/****
	 *
	 * @Title: getTreeByStack
	 * @Description: 獲取樹形結構字符串
	 * @param  nodeAll  全部結點
	 * @param  selectedIds 選中ids
	 * @param  filters
	 * @return String   樹形字符串
	 */
	public static String getTreeByStack(List<?> nodeAll, List<Long> selectedIds, SerializeFilter[] filters){

		if (ArrayUtils.isEmpty(filters)) {
			SimplePropertyPreFilter simplePropertyPreFilter = new SimplePropertyPreFilter();
			filters = new SerializeFilter[]{simplePropertyPreFilter};
		}

		Map<Long, JSONArray> parentMap = new HashMap<>();
		JSONArray rootList = new JSONArray();
        if (!CollectionUtils.isEmpty(nodeAll)) {
            JSONArray jsonListAll = JSONArray.parseArray(JSON.toJSONString(nodeAll,filters));
            for(int i=0;i<jsonListAll.size();i++){
                JSONObject jsonObject = jsonListAll.getJSONObject(i);
				if (!CollectionUtils.isEmpty(selectedIds)) {
					if (selectedIds.contains(jsonObject.getLong("id"))) {
						jsonObject.put("flag", 1);
					}else {
						jsonObject.put("flag", 0);
					}
				}
				if (jsonObject.get("parentId")==null||jsonObject.getLongValue("parentId")==0) {
                    rootList.add(jsonObject);
                    continue;
                }
                Long parentId = jsonObject.getLong("parentId");
                if (CollectionUtils.isEmpty(parentMap.get(parentId))) {
					JSONArray list = new JSONArray();
                    parentMap.put(parentId, list);
                }
                parentMap.get(parentId).add(jsonObject);

            }
        }
		String tree=getTreeByStack( rootList,parentMap);
		return tree;
	}
}
相關文章
相關標籤/搜索