Java实现List转JSONTree形式,两种常⽤⽅式import com.alibaba.fastjson.JSON;
import java.util.ArrayList;
import java.util.List;
public class TreeNode {
private Integer id;
private Integer pid;
lua字符串转数组private String name;
private List<TreeNode> children;
public TreeNode() {
}
public TreeNode(Integer id, Integer pid, String name) {
this.id = id;
this.pid = pid;
this.name = name;
}
public TreeNode(Integer id, Integer pid, String name, List<TreeNode> children) {
this.id = id;
this.pid = pid;
this.name = name;
this.children = children;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getPid() {
return pid;
}
public void setPid(Integer pid) {
this.pid = pid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<TreeNode> getChildren() {
return children;
}
public void setChildren(List<TreeNode> children) {
this.children = children;
}
// 定义转换⽅法1
public static List<TreeNode> listGetTree(List<TreeNode> list){
List<TreeNode> treelist = new ArrayList<>();
for(TreeNode treeNode:list){
// 到各个⽗根,直接插⼊到treeList中,作为初始节点s
Pid() == 0){
treelist.add(treeNode);
}
// 到⼦
for(TreeNode treeNode1:list){
Pid() == Id()){
Children() ==null){
treeNode.setChildren(new ArrayList<TreeNode>());
}
}
}
}
return treelist;
}
// ⽅法⼆,先最⽗级节点,然后递归⼦
public static List<TreeNode> listToTreeByRecursion(List<TreeNode> list){
// 先到最初的⽗节点
List<TreeNode> treeNodeList = new ArrayList<>();
for(TreeNode treeNode: list){
Pid() == 0){
treeNodeList.add(findChildren(treeNode, list));
}
}
return treeNodeList;
}
public static TreeNode findChildren(TreeNode treeNode, List<TreeNode> list){ // 根据⽗节点去递归⼦
for(TreeNode treeNode1: list){
Id() == Pid()){
Children()==null){
treeNode.setChildren(new ArrayList<TreeNode>());
}
}
}
return treeNode;
}
public static void main(String[] args) {
List<TreeNode> list = new ArrayList<TreeNode>();
list.add(new TreeNode(1,0,"1"));
list.add(new TreeNode(2,1,"2"));
list.add(new TreeNode(3,2,"3"));
list.add(new TreeNode(11,0,"11"));
list.add(new TreeNode(21,11,"21"));
list.add(new TreeNode(31,21,"31"));
// ⽅法⼀
List<TreeNode> treelist = new ArrayList<TreeNode>();
treelist = listGetTree(list);
// ⽅式⼆
System.out.println("⽅式⼀:" + JSON(treelist));
List<TreeNode> treelist1 = new ArrayList<TreeNode>();
treelist1 = listToTreeByRecursion(list);
System.out.println("⽅式⼆:" + JSON(treelist1));
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论