java8树形结构封装

458 阅读1分钟
@Test
public void categoryTest(){
    List<ProductCategory>  listAll =  productCategoryService.list().stream().sorted(Comparator.comparing(ProductCategory::getId)).collect(Collectors.toList());

    List<ProductCategory>  collect= listAll.stream().filter(p -> p.getParentId()==0).map(m -> {
        m.setChild(getChildrens(m,listAll));
        return m;
    }).collect(Collectors.toList());
    System.out.println("-------转json输出结果-------");
    System.out.println(JacksonUtils.pojo2json(collect));

}

/**
 * 递归查询子节点
 * @param root 根节点
 * @param listAll 所有节点
 * @return 父节点信息
 */
private List<ProductCategory> getChildrens(ProductCategory root,List<ProductCategory>  listAll){
    List<ProductCategory> children = listAll.stream().filter(p -> p.getParentId().equals(root.getId())).map(m -> {
        m.setChild(getChildrens(m,listAll));
        return  m;
    } ).collect(Collectors.toList());
    return  children;
}