import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
/**
* @desc: 树形结构
*/
@Data
public class TreeTypeDTO {
@ApiModelProperty(value = "ID",required = true)
private String id;
@ApiModelProperty(value = "名称",required = true)
private String name;
@ApiModelProperty(value = "子集",required = true)
private List<TreeTypeDTO> children;
@ApiModelProperty(value = "父级id")
@JsonIgnore
private String parentId;
/**
* 生成树型结构
* @param list
* @return
*/
public static List<TreeTypeDTO> listToTree(List<TreeTypeDTO> list) {
if (CollectionUtils.isEmpty(list)){
return null;
}
//用递归找子。
List<TreeTypeDTO> treeList = new ArrayList<>();
for (TreeTypeDTO tree : list) {
//根目录的parentId为null ,-1
if (StringUtils.isBlank(tree.getParentId()) || StringUtils.equals(tree.getParentId(),"-1")){
treeList.add(findChildren(tree, list));
}
}
return treeList;
}
private static TreeTypeDTO findChildren(TreeTypeDTO tree, List<TreeTypeDTO> list) {
for (TreeTypeDTO node : list) {
if (StringUtils.equals(node.getParentId(),tree.getId())){
if (CollectionUtils.isEmpty(tree.getChildren())){
tree.setChildren(new ArrayList<>());
}
tree.getChildren().add(findChildren(node, list));
}
}
return tree;
}
}
递归生成树型结构
最新推荐文章于 2023-02-06 18:10:27 发布