---
title: "从数据库结果集查找树的根节点"
author: "bocent"
date: "2009-08-14T11:26:05Z"
tags: []
slug: "untitled"
draft: false
lastmod: "2009-08-14T11:26:05Z"
id: 447587
url: "https://bocent.iteye.com/blog/447587"
---

由于在查询出的每条记录里,都有unit\_id和par\_unit\_id,所以只需要找出在unit\_id里没有的par\_unit\_id,则该条记录为根节点,代码如下:

```
public List getRootUnits2(List list){
		List rootList = new ArrayList();
		for(int i=0; i < list.size(); i++){
			boolean isRoot = true;
			for(int j=0; j< list.size();j++){
				Map parMap = (Map)list.get(i);
				Map map = (Map)list.get(j);
				if(StringUtils.equals((String)parMap.get("par_unit_id"), (String)map.get("unit_id"))){
					isRoot = false;
					break; //找到了父节点
				}
			}
			if(isRoot){
				rootList.add(list.get(i));
			}
		}
		return rootList;
	}
```