java递归生成树结构的数据

痴心易碎 提交于 2021-01-06 04:29:43
@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);
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!