package 功能;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class TreeMenu {
static List<Tree> list=new ArrayList<>();
static {
list.add(new Tree(1,"父亲",0));
list.add(new Tree(2,"儿子1",1));
list.add(new Tree(3,"女儿1",1));
list.add(new Tree(4,"孙子1",2));
list.add(new Tree(5,"外甥1",3));
list.add(new Tree(6,"孙子2",2));
list.add(new Tree(6,"孙女1",2));
}
@Test
public void treeMenu(){
HashMap<String, List<Tree>> map = new HashMap<>();
List<JSONObject> treeList=new ArrayList<>();
List<Tree> treeStream = list.stream().filter((tree) -> {
return tree.getpId() == 0;
}).collect(Collectors.toList());
for (Tree tree : treeStream){
JSONObject jsonObject=new JSONObject();
jsonObject.put("name",tree.getName());
jsonObject.put("chirldrens",getChirldrens(tree.getId()));
treeList.add(jsonObject);
}
System.out.println(JSON.toJSONString(treeList));
}
private List<JSONObject> getChirldrens(Integer id) {
List<JSONObject> objects = new ArrayList<>();
List<Tree> childs=list.stream().filter(tree -> tree.getpId()==id).collect(Collectors.toList());
childs.forEach(tree -> {
JSONObject jsonObject=new JSONObject();
jsonObject.put("name",tree.getName());
jsonObject.put("chirldrens",getChirldrens(tree.getId()));
objects.add(jsonObject);
});
return objects;
}
static class Tree {
Integer id;
String name;
Integer pId;
public Tree(Integer id, String name, Integer pId) {
this.id = id;
this.name = name;
this.pId = pId;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getpId() {
return pId;
}
public void setpId(Integer pId) {
this.pId = pId;
}
}
}