---
title: "将数据库树形记录转为java 树形数据结构"
author: "JavaSam"
date: "2014-08-24T18:36:54Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2014-08-24T18:36:54Z"
id: 2108312
url: "https://javasam.iteye.com/blog/2108312"
---

```
    /**
	 * 转换为Tree结构
	 * @param treedata
	 * @return
	 */
	public static Tree toTreeList(List<Tree> treedata){
		Tree root = null;
		for(Tree node:treedata){
			String parentid = node.getParentid();
			if(parentid.equals("0"))
				root = node;
		    Tree parent = getTarget(treedata,parentid); 
		    if(parent != null){
		    	List<Tree> children = parent.getChildren();
		    	if(children == null){
		    		children = new ArrayList<Tree>();
		    		parent.setChildren(children);
		    	}
		        children.add(node);
		    }
		}
		return root;
	}
	/**
	 * 获得指定节点
	 * @param treedata
	 * @param id
	 * @return
	 */
	private static Tree getTarget(List<Tree> treedata,String id){
		for(Tree node:treedata){
			String _id = node.getId();
			if(_id.equals(id))
				return node;
		}
		return null;
	}
```