List实现树状结构

246 阅读1分钟

java代码

处理主键字符串类型数据;感谢java是引用传递。

        public interface TreeDataInter<T> {
        	public String getParentId(T t);//获取父节点id
        	public String getCurrentId(T t);//获取当前节点id
        	public void addSubId(T parent,T sub);//将当前节点加入父节点
        }
        //List树状结构
	public static <T> List<T> sortTreeData(List<T> list,TreeDataInter<T> td){
		//改变数据结构  menuId,对象
		Map<String,T> m=CollectionUtils.instanceMap();
		for(T t:list){
			m.put(td.getCurrentId(t), t);
		}
		//插入子菜单
		Iterator<T> ite = list.iterator();
		while(ite.hasNext()){
			T next = ite.next();
			String pId=td.getParentId(next);
			if(m.containsKey(pId)){
				td.addSubId(m.get(pId), next);
				ite.remove();
			}
		}
		return list;
	}

测试结果

	@Test
	public void testForTree(){
		List<Map<String,Object>> l=CollectionUtils.instanceList();
		Map<String,Object> m=CollectionUtils.instanceMap();m.put("id", "1");m.put("subList", new ArrayList<Map<String,Object>>());l.add(m);
		Map<String,Object> m1=CollectionUtils.instanceMap();m1.put("id", "2");m1.put("parentId", "1");m1.put("subList", new ArrayList<Map<String,Object>>());l.add(m1);
		Map<String,Object> m2=CollectionUtils.instanceMap();m2.put("id", "3");m2.put("parentId", "1");m2.put("subList", new ArrayList<Map<String,Object>>());l.add(m2);
		System.out.println(JSONUtils.toJSONString(l));
		l=CollectionUtils.sortTreeData(l, new TreeDataInter<Map<String,Object>>() {
			@Override
			public void addSubId(Map<String,Object> parent, Map<String,Object> sub) {
				List<Map> s=(List<Map>) parent.get("subList");
				s.add(sub);
				
			}
			@Override
			public String getParentId(Map<String,Object> t) {
				return (String) t.get("parentId");
			}
			@Override
			public String getCurrentId(Map<String,Object> t) {
				return (String) t.get("id");
			}
		});
		System.out.println(JSONUtils.toJSONString(l));
	}

测试结果