无限极分类JAVA 实现—查子孙树、家谱树
效果展示:
import java.util.*;
public class Test {
List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
Set<String> _search_id = new HashSet<String>();
Set<String> _search_pid = new HashSet<String>();
@org.junit.Test
public void demo() {
data.add(new HashMap<String, Object>() {{
put("id", "1");
put("pid", "0");
put("name", "部门ID-1");
}});
data.add(new HashMap<String, Object>() {{
put("id", "2");
put("pid", "0");
put("name", "部门ID-2");
}});
data.add(new HashMap<String, Object>() {{
put("id", "3");
put("pid", "0");
put("name", "部门ID-3");
}});
data.add(new HashMap<String, Object>() {{
put("id", "4");
put("pid", "1");
put("name", "部门ID-1-4");
}});
data.add(new HashMap<String, Object>() {{
put("id", "5");
put("pid", "1");
put("name", "部门ID-1-5");
}});
data.add(new HashMap<String, Object>() {{
put("id", "6");
put("pid", "5");
put("name", "部门ID-5-6");
}});
data.add(new HashMap<String, Object>() {{
put("id", "7");
put("pid", "5");
put("name", "部门ID-5-6");
}});
data.add(new HashMap<String, Object>() {{
put("id", "8");
put("pid", "6");
put("name", "部门ID-5-6");
}});
Set<String> son = search_id(data, "5");
System.out.println("找子孙" + son);
Set<String> father = search_pid(data, "6");
System.out.println("找家谱" + father);
}
//查找子孙树
public Set<String> search_id(List<HashMap<String, Object>> data, String id) {
for (int i = 0; i < data.size(); i++) {
Object objPid = data.get(i).get("pid");
if (objPid != null) {
if (objPid.equals(id)) {
Object objId = data.get(i).get("id");
_search_id.add(objId.toString());
search_id(data, objId.toString());
}
}
}
return _search_id;
}
//查找 家谱树
public Set<String> search_pid(List<HashMap<String, Object>> data, String pid) {
for (int i = 0; i < data.size(); i++) {
Object objPid = data.get(i).get("id");
if (objPid != null) {
if (objPid.equals(pid)) {
Object objId = data.get(i).get("pid");
_search_pid.add(objId.toString());
search_pid(data, objId.toString());
}
}
}
return _search_pid;
}
}
|