一个使用stream流式编程结合递归的例子
public List<CategoryEntity> listWithTree() {
List<CategoryEntity> categoryEntities = this.list();
List<CategoryEntity> categoryEntities0 = categoryEntities.stream().filter((categoryEntity) -> {
return categoryEntity.getParentCid() == 0;
}).map((categoryEntity)->{
categoryEntity.setChildren(getChildren(categoryEntity,categoryEntities));
return categoryEntity;
}).sorted((categoryEntity1,categoryEntity2)->{
return (categoryEntity1.getSort()==null?0:categoryEntity1.getSort())-(categoryEntity2.getSort()==null?0:categoryEntity2.getSort());
}).collect(Collectors.toList());
return categoryEntities0;
}
private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {
List<CategoryEntity> children = all.stream().filter((categoryEntity) -> {
return categoryEntity.getParentCid() == root.getCatId();
}).map((categoryEntity) -> {
categoryEntity.setChildren(getChildren(categoryEntity, all));
return categoryEntity;
}).sorted((categoryEntity1, categoryEntity2) -> {
return (categoryEntity1.getSort()==null?0:categoryEntity1.getSort())-(categoryEntity2.getSort()==null?0:categoryEntity2.getSort());
}).collect(Collectors.toList());
return children;
}