java 8 遞歸 並且根據某個字段排序


1.實體bean結構
public class DmpDictVo {
@ApiModelProperty(value = "數據id")
private String id;

@ApiModelProperty(value = "父id")
private String pid;

@ApiModelProperty(value = "描述")
private String name;

  //初始化 children 避免報空指針異常
    List<DmpDictVo> children = new ArrayList<>();
}


// 根據自己的業務編寫
private List<DmpDictVo> searchFatherDmpDict() {
 // 查詢出所有的數據字典
List<QaCategoryVo> qaCategoryVoList = findAll(type);
// 遞歸封裝數據

return makeTree(qaCategoryVoList, -1L);
 
        
}


/**
* 遞歸方法構造
*/

private List<QaCategoryVo> makeTree(List<QaCategoryVo> departmentList, Long pId) {

//子類
List<QaCategoryVo> children = departmentList.stream().filter(x -> x.getPid().equals(pId)).collect(Collectors.toList());
// 排序
children = children.stream().sorted(Comparator.comparing(QaCategoryVo::getSort, Comparator.nullsLast(Integer::compareTo)).reversed()).collect(Collectors.toList());
  
if(children.isEmpty()){
return null;
}
//后輩中的非子類
List<QaCategoryVo> successor = departmentList.stream().filter(x -> !x.getPid().equals(pId)).collect(Collectors.toList());

for (QaCategoryVo x : children) {
List<QaCategoryVo> qaCategoryVos = makeTree(successor, x.getId());
x.setChildren(qaCategoryVos);
}
return children;

}


免責聲明!

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



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