Stream实现递归查询树形结构

Stream实现递归查询树形结构

一、简单应用

/**
 * Stream实现递归查询树形结构
 */
public class TreeStructure {
    /**
     * 先获取父级
     * @param list
     * @return
     */
    public static List<tree> getTreeStructure(List<tree> list){
        return list.stream().filter(tree -> tree.getPid()==0).peek(tree -> tree.setChildTree(getChildTree(tree,list))).collect(Collectors.toList());
    }

    /**
     * 递归存储子树
     * @param tree
     * @param list
     * @return
     */
    private static List<tree> getChildTree(tree tree, List<tree> list) {
        return list.stream().filter(tr->tr.getPid()==tree.getId()).map(tr->{//这儿map的写法等价于peek
            tr.setChildTree(getChildTree(tr,list));
                    return tr;
        }).collect(Collectors.toList());
    }
}

/**
 * 测试类
 * 父级id为0表示没有父级id
 */
@Data
@ToString
class tree{
    //主键id
    private int id;
    //父级id
    private int pid;
    //子树
    private List<tree> childTree = new ArrayList<>();

    public tree(int id, int pid) {
        this.id=id;
        this.pid=pid;
    }
}

class test{
    public static List<tree> testData(){
        return new ArrayList<tree>(){{
            add(new tree(1,0));
            add(new tree(2,0));
            add(new tree(3,0));
            add(new tree(4,1));
            add(new tree(5,2));
            add(new tree(6,3));
            add(new tree(7,4));
            add(new tree(8,5));
            add(new tree(9,6));
        }};
    }
    public static void main(String[] args) {
        System.out.println(JSON.toJSONString(TreeStructure.getTreeStructure(testData())));
    }
}

你可能感兴趣的:(Java,java)