/**
* @ClassName: TreeParser
* @Description: TODO(树解析工具类)
* @author xushaowen
* @date 2018年11月21日 上午11:30:57
*
*/
public class TreeParser{
public interface TreeEntity<E> {
public String getId();
public String getPid();
public void setChildList(List<E> childList);
}
/**
* 解析树形数据
* @param topId 根节点id
* @param entityList 所有的
*/
public static <E extends TreeEntity<E>> List<E> getTreeList(String topId, List<E> entityList) {
List<E> resultList=new ArrayList<E>();
//获取顶层元素集合
String parentId;
for (E entity : entityList) {
parentId=entity.getPid();
if(parentId==null||topId.equals(parentId)){
resultList.add(entity);
}
}
//获取每个顶层元素的子数据集合
for (E entity : resultList) {
entity.setChildList(getSubList(entity.getId(),entityList));
}
return resultList;
}
/**
* 获取子数据集合
* @param id
* @param entityList
*/
private static <E extends TreeEntity<E>> List<E> getSubList(String id, List<E> entityList) {
List<E> childList=new ArrayList<E>();
String parentId;
//子集的直接子对象
for (E entity : entityList) {
parentId=entity.getPid();
if(id.equals(parentId)){
childList.add(entity);
}
}
//子集的间接子对象
for (E entity : childList) {
entity.setChildList(getSubList(entity.getId(), entityList));
}
//递归退出条件
if(childList.size()==0){
return null;
}
return childList;
}
}
需要进行树封装的实体只需要实现工具类的TreeEntity接口即可 如:
public class EsbFieldRelationModel implements TreeParser.TreeEntity<EsbFieldRelationModel>, Serializable {
/**
* 主键
*/
private String id;
/**
* 父id
*/
private String pid;
/**
* 字段中文名称
*/
private String zdmc;
/**
* 拼音简拼
*/
private String pyjp;
/**
* 数据来源表名称
*/
private String sjly;
/**
* 数据字段
*/
private String sjzd;
/**
* 子集
*/
private List<EsbFieldRelationModel> childList;
private static final long serialVersionUID = 1L;
public String getId() {
return id;
}
@Override
public void setChildList(List<EsbFieldRelationModel> childList) {
this.childList=childList;
}
public List<EsbFieldRelationModel> getChildList() {
return childList;
}
public void setId(String id) {
this.id = id == null ? null : id.trim();
}
@Override
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid == null ? null : pid.trim();
}
public String getZdmc() {
return zdmc;
}
public void setZdmc(String zdmc) {
this.zdmc = zdmc == null ? null : zdmc.trim();
}
public String getPyjp() {
return pyjp;
}
public void setPyjp(String pyjp) {
this.pyjp = pyjp == null ? null : pyjp.trim();
}
public String getSjly() {
return sjly;
}
public void setSjly(String sjly) {
this.sjly = sjly == null ? null : sjly.trim();
}
public String getSjzd() {
return sjzd;
}
public void setSjzd(String sjzd) {
this.sjzd = sjzd == null ? null : sjzd.trim();
}
}
后续只需要进行调用工具类的解析树形数据方法,即可将实体封装成树结构