public abstract class List2TreeUtils<T> {
protected abstract String getId(T node);
protected abstract String getParentId(T node);
protected abstract List<T> getChildList(T node);
protected abstract void setChildList(List<T> childList,T parent);
/**
* 数组转树
* @param oldList
* @return
*/
public List<T> list2Tree(List<T> oldList) {
Map<String,Object> newMap = new HashMap<>(oldList.size());
List<T> newList = new ArrayList<>();
for (T tree : oldList){
newMap.put(getId(tree),tree);
}
for (T tree : oldList){
T parent = (T) newMap.get(getParentId(tree));
if (parent != null){
List<T> childList = getChildList(parent);
if (childList == null){
childList = new ArrayList<>();
}
childList.add(tree);
setChildList(childList,parent);
}else {
if(StringUtils.isEmpty(getParentId(tree))){
newList.add(tree);
}
}
}
return newList;
}
}
java数组转树工具类
最新推荐文章于 2023-05-21 17:04:52 发布