java 二级列表 stream流实现
效果:
表数据的样子
代码:
public Result secondaryList() {
List<MachineryType> machineryTypes = machineryTypeMapper.selectList(new QueryWrapper<MachineryType>().orderByAsc("pid"));
// 创建父子关系
Map<Integer, MachineryType> machineryTypeMap = machineryTypes.stream()
.collect(Collectors.toMap(MachineryType::getId, c -> c));
List<MachineryType> outList = machineryTypes.stream()
.filter(c -> c.getPid() == 0) // 过滤出父节点
.peek(parent -> {
List<MachineryType> children = machineryTypes.stream()
.filter(child -> child.getPid().equals(parent.getId()))
.collect(Collectors.toList());
parent.setChildren(children); // 设置子节点
})
.collect(Collectors.toList());
return Result.success(outList);
}