java遞歸生成樹結構的數據


@Data
@EqualsAndHashCode(callSuper =true)
@ApiModel(value = "AccountCaptionVo", description = "會計科目")
public class AccountCaptionVo extends BaseModel {

@ApiModelProperty(value ="會計科目名稱",name = "captionName")
private String captionName;

@ApiModelProperty(value = "會計科目編碼",name = "captionCode")
private String captionCode;

@ApiModelProperty(value = "父類編碼",name = "parentId")
private Long parentId;

@ApiModelProperty(value = "系統科目",name = "systematicSubjects")
private String systematicSubjects;

@ApiModelProperty(value = "借貸方向",name = "lendingDirection")
private String lendingDirection;

@ApiModelProperty(value = "子集",name = "children")
private List<AccountCaptionVo> children;

@ApiModelProperty(value = "科目名稱助記碼",name = "mnemonicCode")
private String mnemonicCode;



public static List<AccountCaptionVo> listToTree(List<AccountCaptionVo> list) {
//用遞歸找子。
List<AccountCaptionVo> treeList = new ArrayList<AccountCaptionVo>();
for (AccountCaptionVo tree : list) {
//根目錄的parentId為-1
if (tree.getParentId() == -1 ) {
treeList.add(findChildren(tree, list));
}
}
return treeList;
}

private static AccountCaptionVo findChildren(AccountCaptionVo tree, List<AccountCaptionVo> list) {
for (AccountCaptionVo node : list) {
if (node.getParentId().longValue() == tree.getId().longValue()) {
if (tree.getChildren() == null) {
tree.setChildren(new ArrayList<AccountCaptionVo>());
}
tree.getChildren().add(findChildren(node, list));
}
}
return tree;
}

@GetMapping(path="")
@ApiOperation(value="獲取所有會計科目",nickname="getAccountCaption")
public Iterable<AccountCaptionVo> List(){
List<AccountCaption> listAccountCaption= capAccountRepository.selecttSql();
List<AccountCaptionVo> listAccountCaptionVos=new ArrayList<>();
listAccountCaption.stream().forEach(x->
{
AccountCaptionVo AccountCaptionVo=new AccountCaptionVo();
try {
BeanUtils.copyProperties(AccountCaptionVo,x);
listAccountCaptionVos.add(AccountCaptionVo);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
});
return listToTree(listAccountCaptionVos);
}


免責聲明!

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



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