自定义实体类:
public class AreaBean {
private Integer level;
private String code;
private String name;
private String pCode;
private String isV;
private List<AreaBean> ch = new ArrayList<AreaBean>();
public Integer getLevel() {
return level;
}
public void setLevel(Integer level) {
this.level = level;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getpCode() {
return pCode;
}
public void setpCode(String pCode) {
this.pCode = pCode;
}
public String getIsV() {
return isV;
}
public void setIsV(String isV) {
this.isV = isV;
}
public List<AreaBean> getCh() {
return ch;
}
public void setCh(List<AreaBean> ch) {
this.ch = ch;
}
@Override
public String toString() {
return "level:" + level + ", code:" + code + ", name:" + name + ", pCode:" + pCode + ", isV:" + isV
+ ", ch:" + ch;
}
}
转树结构工具 类:
public class Tool {
public static List<AreaBean> transDepartment(List<AreaBean> rootList){
List<AreaBean> nodeList = new ArrayList<AreaBean>();
for (AreaBean areaBean : rootList) {
if ("87".equals(areaBean.getCode())){//表明是一级父类
nodeList.add(areaBean);
}
areaBean.setCh(setChild(areaBean.getCode(),rootList));
}
return nodeList;
}
public static List<AreaBean> setChild(String id, List<AreaBean> list ){
List<AreaBean> childList = new ArrayList<>();
for (AreaBean areaBean : list) {
if (id.equals(areaBean.getpCode())){
childList.add(areaBean);
}
}
for (AreaBean areaBean : childList) {
areaBean.setCh(setChild(areaBean.getCode(),list));
}
if (childList.size()==0){
return null;
}
return childList;
}
}
使用方式
public static void main(String[] args) {
AreaBean a = new AreaBean();
a.setLevel(1);
a.setCode("87");
a.setName("aa");
a.setpCode("-1");
AreaBean a1 = new AreaBean();
a1.setLevel(2);
a1.setCode("871");
a1.setName("a1");
a1.setpCode("87");
AreaBean a2 = new AreaBean();
a2.setLevel(3);
a2.setCode("8711");
a2.setName("a3");
a2.setpCode("871");
AreaBean a3 = new AreaBean();
a3.setLevel(3);
a3.setCode("8712");
a3.setName("a3");
a3.setpCode("871");
AreaBean a4 = new AreaBean();
a4.setLevel(2);
a4.setCode("872");
a4.setName("a4");
a4.setpCode("87");
AreaBean a5 = new AreaBean();
a5.setLevel(3);
a5.setCode("8721");
a5.setName("a5");
a5.setpCode("872");
AreaBean a6 = new AreaBean();
a6.setLevel(3);
a6.setCode("8722");
a6.setName("a6");
a6.setpCode("872");
List<AreaBean> list = new ArrayList<AreaBean>();
list.add(a);
list.add(a1);
list.add(a2);
list.add(a3);
list.add(a4);
list.add(a5);
list.add(a6);
List<AreaBean> lists = Tool.transDepartment(list);
List<AreaBean> te = Tool.treeAreaList(lists, a4.getCode());
System.out.println(te.toString());
}