dictCode parentCode是父子级关系,可以对应修改成id和parentId
树形工具类 TreeUtil.java
import com.bmsoft.voice.entity.dto.TreeDTO;
import java.util.ArrayList;
import java.util.List;
/**
* @author 23Legend
*/
public class TreeUtil {
/**
* 使用递归方法建树
* @param list
* @return
*/
public static <T extends TreeDTO> List<T> buildByRecursive(List<T> list) {
List<T> trees = new ArrayList<T>();
for (T t : list) {
if (null == t.getParentCode()) {
trees.add(findChildren(t, list));
}
}
return trees;
}
/**
* 递归查找子节点
* @param list
* @return
*/
public static <T extends TreeDTO> T findChildren(T root, List<T> list) {
root.setChildren(new ArrayList<T>());
for (T it : list) {
if (root.getDictCode().equals(it.getParentCode())) {
if (root.getChildren() == null) {
root.setChildren(new ArrayList<T>());
}
root.getChildren().add(findChildren(it, list));
}
}
return root;
}
public static <T extends TreeDTO> List<T> getTress(List<T> root) {
for (int i = 0; i < root.size(); i++) {
// 查询某节点的子节点(获取的是list)
List<T> children = new ArrayList<T>();
if (null != root.get(i).getChildren()) {
children = root.get(i).getChildren();
}
getTress(children);
}
return root;
}
public static <T extends TreeDTO> List<T> getByParent(List<T> list,String pid) throws Exception{
List<T> childList = new ArrayList<T>();
for (T item : list) {
if (item != null) {
// 判断当前节点的父节点是不是pid
if (pid.equals(item.getParentCode())) {
List<T> child = getByParent(list, item.getDictCode());
item.setChildren(child);
childList.add(item);
}
}
}
return getTress(childList);
}
public static <T extends TreeDTO> List<String> getCodes(List<T> root, List<String> result){
for (int i = 0; i < root.size(); i++) {
// 查询某节点的子节点(获取的是list) 前序遍历
result.add(root.get(i).getDictCode());
if (null != root.get(i).getChildren()) {
List<T> children = root.get(i).getChildren();
getCodes(children,result);
}
//result.add(root.get(i).getId());//后序遍历
}
return result;
}
}
树形数据继承 TreeDTO.java (swagger相关可以去除)
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.List;
/**
* @author 23Legend
*/
@Data
@ApiModel("树形数据公共类")
public class TreeDTO<T> {
@ApiModelProperty(value = "ID")
private Long id;
@ApiModelProperty(value = "code")
private String dictCode;
@ApiModelProperty("父级code")
private String parentCode;
@ApiModelProperty("子级集")
private List<T> children;
}
使用
// 封装层级以及层级的作有子级code
List<String> codes = Lists.newArrayList();
if (Optional.ofNullable(request.getPages()).isPresent() && !request.getPages().isEmpty()) {
List<SysDictDTO> list = transform2DTO();
request.getPages().stream().forEach(item -> {
try {
List<SysDictDTO> byParent = TreeUtil.getByParent(list, item);
if (null != byParent && !byParent.isEmpty()){
TreeUtil.getCodes(byParent, codes);
}
} catch (Exception e) {
e.printStackTrace();
}
});
codes.addAll(request.getPages());
}
注意继承类:?
@Data
@ApiModel(value = "字典传输对象")
public class SysDictDTO extends TreeDTO{}
|