import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.yj.lf.domain.AjaxResult;
/***
* 递归树形结构工具类
*/
public class TreeUtil {
public static TreeSelectVo treeVo = new TreeSelectVo();
public static List<String> ids = new ArrayList<String>();
public static Map<String, List<TreeSelectVo>> pathMap = new HashMap<String, List<TreeSelectVo>>();// 记录所有从根节点到叶子结点的路径
// 过滤一下数据
public static AjaxResult filter(AjaxResult res, String type) {
List<TreeSelectVo> list = new ArrayList<TreeSelectVo>();
if (HttpStatus.SUCCESS == res.getCode()) {
list = (List<TreeSelectVo>) JSONArray.parseArray(JSON.toJSONString(res.get("data")), TreeSelectVo.class);
return AjaxResult.success(list);
}
return res;
}
// 递归计算父类别下子类别集合
public static List<String> recursive(List<TreeSelectVo> tree) {
List<String> list = new ArrayList<String>();
for (TreeSelectVo treeSelectVo : tree) {
list.add(treeSelectVo.getId());
if (treeSelectVo.getChildren().size() > 0) {
list.addAll(recursive(treeSelectVo.getChildren()));
}
}
return list;
}
// 递归计算父类别特定子类需要全局变量跳出递归
public static TreeSelectVo find(List<TreeSelectVo> tree, String id) {
treeVo = new TreeSelectVo();// 初始化全局变量
return findDetail(tree, id);
}
// 递归计算父类别特定子类
public static TreeSelectVo findDetail(List<TreeSelectVo> tree, String id) {
for (TreeSelectVo treeSelectVo : tree) {
if (id.equals(treeSelectVo.getId())) {
treeVo = treeSelectVo;
} else if (treeSelectVo.getChildren().size() > 0) {
findDetail(treeSelectVo.getChildren(), id);
}
}
return treeVo;
}
// 递归计算父类用-分隔-代表路径
public static String getParentNames(List<TreeSelectVo> tree, String id) {
return String.join("-", findParentNames(tree, id));
}
// 递归计算父类名称集合
public static List<String> findParentNames(List<TreeSelectVo> tree, String id) {
ids = new ArrayList<String>();// 初始化全局变量
return findParentName(tree, id);
}
// 递归子类递归父类NAME集合
public static List<String> findParentName(List<TreeSelectVo> tree, String id) {
TreeSelectVo vo = find(tree, id);
if (StringUtils.isNotEmpty(vo.getParentId())) {
ids.add(vo.getLabel());
findParentName(tree, vo.getParentId());
} else {
ids.add(vo.getLabel());
}
Collections.reverse(ids);
return ids;
}
// 递归计算父类ID集合
public static List<String> findParentIds(List<TreeSelectVo> tree, String id) {
ids = new ArrayList<String>();// 初始化全局变量
return findParentId(tree, id);
}
// 子类反向递归父类ID集合
public static List<String> findParentId(List<TreeSelectVo> tree, String id) {
TreeSelectVo vo = find(tree, id);
if (StringUtils.isNotEmpty(vo.getParentId())) {
ids.add(vo.getId());
findParentId(tree, vo.getParentId());
} else {
ids.add(vo.getId());
}
Collections.reverse(ids);
return ids;
}
}