查询树形目录(内存遍历成树返回)

实体

@Data
@TableName("dtp_sm_servicetype")
@ApiModel(value = "SmServicetype对象", description = "服务类型")
@EqualsAndHashCode(callSuper = true)
public class SmServicetype extends BaseEntity {

	@ApiModelProperty("服务类型名称")
	private String name;
	@ApiModelProperty("服务标题")
	private String title;
	@ApiModelProperty("服务分类描述")
	private String descinfo;
	@ApiModelProperty("服务分类父节点编号")
	private Long parentId;
	@ApiModelProperty("排序")
	private Integer orderIndex;

	// 存储下(子)级节点信息
	@TableField(exist = false)
	private List<SmServicetype> childrenList;
}


调用

/**
 * 服务类型 分页
 */
@ApiOperation(value = "查询所有服务类型", notes = "传入smServicetype")
public R<List<SmServicetypeVO>> serviceTypeTree(SmServicetype smServicetype) {
	//查询所有树数据list
	List<SmServicetype> allList = smServicetypeService.list();
	// 内存中递归成树
	List<SmServicetype> typeTreeList = this.selectSmServicetypeTrees(allList);
	return R.data(SmServicetypeWrapper.build().listVO(typeTreeList));
}

private List<SmServicetype> selectSmServicetypeTrees(List<SmServicetype> smServicetypeList) {
	List<SmServicetype> collect = smServicetypeList.stream()
		.filter(item -> item.getParentId() == -1)   //ParentId=-1的节点为根节点(根据具体情况修改)    filter为过滤不符合条件的
		.map(item -> {
			item.setChildrenList(getChildrenList(item, smServicetypeList));
			return item;
		})
		.collect(Collectors.toList());
	return collect.size() == 0 ? smServicetypeList : collect;

}

private List<SmServicetype> getChildrenList(SmServicetype smServicetype, List<SmServicetype> smServicetypeList) {
	List<SmServicetype> collect = smServicetypeList.stream()
		.filter(item -> item.getParentId().equals(smServicetype.getId()))
		.map(item -> {
			item.setChildrenList(getChildrenList(item, smServicetypeList));
			return item;
		})
		.collect(Collectors.toList());
	return collect;
}

你可能感兴趣的:(Java代码,目录树,java)