Stream與遞歸使用


(一)Stream 好用

  

 
         
@Override
public List<CategoryEntity> listWithTree() {

//1 查出所有分類
List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
//2 組裝成父子的樹形結構
//2.1 找到所有一級分類
List<CategoryEntity> level1Menus = categoryEntities.stream().filter((categoryEntitie) -> {
return categoryEntitie.getParentCid() == 0;
}).map(menu -> {
menu.setChildren(getChildrens(menu,categoryEntities));
return menu;
}).sorted((menu1,menu2) -> {
return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
}).collect(Collectors.toList());

return level1Menus;
}


private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> all){

List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
        return categoryEntity.getParentCid().equals(root.getCatId());
}).map((categoryEntity) -> {
//找子菜單 遞歸
categoryEntity.setChildren(getChildrens(categoryEntity, all));
return categoryEntity;
}).sorted((menu1, menu2) -> {
//排序
return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
}).collect(Collectors.toList());

return children;
}
 

 

 


 

 

 

    我看過沙漠下暴雨

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM