Java-stream处理单表树形结构
单表省市区,用stream流处理
@ApiModel("地区代码")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class SysAreaCode {
@ApiModelProperty(value = "地区代码id")
private Long areaId;
@ApiModelProperty(value = "父Id")
private Long parentId;
@ApiModelProperty(value = "祖集列表")
private String ancetors;
@ApiModelProperty(value = "地区代码名称")
private String areaName;
@ApiModelProperty(value = "状态")
private String state;
@TableLogic
//删除标记,这个注解会让plus,每次都携带del_flag=0这个条件
@ApiModelProperty(value = "是否删除")
private String delFlag;
@ApiModelProperty(value = "创建者")
private Long createBy;
@ApiModelProperty(value = "创建时间")
private Date createTime;
@ApiModelProperty(value = "子类集")
@TableField(exist = false)
//这里用的是mybatisplus,这个注解是说明这个字段不是数据库存在的字段
private List<SysAreaCode> childers;
}
@ApiOperation("区域code树形")
@GetMapping("/getAreaCodeTrees")
public R<List<SysAreaCode>> getAreaCodeTrees(){
List<SysAreaCode> vo = sysAreaCodeService.selectTrees();
return R.ok(vo);
}
public interface SysAreaCodeService {
List<SysAreaCode> selectTrees();
}
@Service
public class SysAreaCodeServiceImpl implements SysAreaCodeService {
@Autowired
private SysAreaCodeMapper sysAreaCodeMapper;
@Override
public List<SysAreaCode> selectTrees() {
List<SysAreaCode> sysAreaCodes = sysAreaCodeMapper.selectList();
//拿到顶级的省,数据库是bigint,实体是Long类型,所以这里需要是0L
List<SysAreaCode> collect = sysAreaCodes.stream().filter(item -> item.getParentId().equals(0L))
.map(item -> {
item.setChilders(getChildres(sysAreaCodes, item));
//返回的item是顶级-省份
return item;
}).collect(Collectors.toList());
return collect;
}
private List<SysAreaCode> getChildres(List<SysAreaCode> sysAreaCodes, SysAreaCode item) {
List<SysAreaCode> collect = sysAreaCodes.stream().filter(items -> items.getParentId().equals(item.getAreaId()))
.map(items -> {
items.setChilders(getChildres(sysAreaCodes, items));
return items;
}).collect(Collectors.toList());
return collect;
}
}
运行结果
分析,每一级的areaId作为下一级的parentId
debug断点调试代码