樹形結構數據生成樹

package test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSONObject;

/**
 * 
 * @author yg
 */
@SuppressWarnings({"rawtypes","unchecked","unused"})
public class TreeUtil {
	public String cIdName;
	public String pIdName;
	public String childListName;
	public List<Map<String,Object>> resultMap=new ArrayList<>();
	public List<Map<String,Object>> dataMap;
	/**
	 * @param cId 子節點名字
	 * @param pId 父節點名字
	 * @param dataMap
	 */
	public TreeUtil(String cIdName, String pIdName,String childListName,List<Map<String,Object>> dataMap) {
		super();
		this.cIdName = cIdName;
		this.childListName = childListName==null?"childList":childListName;
		this.pIdName = pIdName;
		this.dataMap = dataMap;
	}

	public  List<Map<String,Object>> getTree(){
		String cId;
		String pId;
		String cId2;
		String pId2;
		boolean hasParent=false;
		for (Map map : dataMap) {
			//判斷每個數據是否有父節點
			cId = map.get(cIdName).toString();
			pId = map.get(pIdName).toString();
			if(!"0".equals(pId)){
				for (Map map2 : dataMap) {
					cId2 = map2.get(cIdName).toString();
					pId2 = map2.get(pIdName).toString();
					if(pId.equals(cId2)){
						//有父節點  map是map2的兒子
						hasParent=true;
						List<Map<String,Object>> childList= (List<Map<String,Object>>)map2.get(childListName);
						if(childList==null){
							childList = new ArrayList<Map<String,Object>>();
							map2.put(childListName, childList);
						}
						childList.add(map);
					}
				}
			}
			if(!hasParent){
				resultMap.add(map);
			}
		}
		return resultMap;
	}
	
	public static void main(String[] args) {
		String a="[{\"cId\":1,\"pId\":0,\"name\":\"11\"},{\"cId\":2,\"pId\":0,\"name\":\"22\"},{\"cId\":3,\"pId\":0,\"name\":\"33\"},{\"cId\":4,\"pId\":1,\"name\":\"41\"},{\"cId\":5,\"pId\":1,\"name\":\"51\"},{\"cId\":6,\"pId\":2,\"name\":\"61\"},{\"cId\":7,\"pId\":3,\"name\":\"71\"},{\"cId\":8,\"pId\":4,\"name\":\"81\"},{\"cId\":9,\"pId\":4,\"name\":\"91\"}]";
		List<Map> map =JSONObject.parseArray(a, Map.class);
		List<Map<String,Object>> data = new ArrayList<>();
		for (Map map2 : map) {
			data.add((Map<String,Object>)map2);
		}
		TreeUtil treeUtil = new TreeUtil("cId", "pId", null, data);
		List<Map<String,Object>> tree = treeUtil.getTree();
		System.out.println(JSONObject.toJSONString(tree));
		
		
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章