废话不多说,上代码 @Data public class MesDeviceTreeDto implements Serializable { private static final long serialVersionUID = 3158036267336648413L; private String id; private String pId; private String no; private String name; private String type; private Integer disLevel; private String text; /** * 子区 */ private String label; private String value; private List<MesDeviceTreeDto> children = new ArrayList<>(); }
@Override public List<MesDeviceTreeDto> findTreeList() { //查询全部 List<MesDeviceTree> allList = mesDeviceTreeRepository.findAllList(); List<MesDeviceTreeDto> mesDeviceTreeDtos = mesDeviceTreeMapper.toDto(allList); ArrayList<MesDeviceTreeDto> list = new ArrayList<>(); for (MesDeviceTreeDto mesDeviceTreeDto : mesDeviceTreeDtos) { mesDeviceTreeDto.setLabel(mesDeviceTreeDto.getName()); mesDeviceTreeDto.setValue(mesDeviceTreeDto.getId()); list.add(mesDeviceTreeDto); } //获取父节点,0表示父节点 List<MesDeviceTreeDto> collect = list.stream().filter(e -> e.getPId().equals("0")).map(e -> { e.setChildren(getChildrens(e, list)); return e; }).collect(Collectors.toList()); return collect; } /** * 递归查询子节点 * @param root * @return */ private List<MesDeviceTreeDto> getChildrens(MesDeviceTreeDto root, List<MesDeviceTreeDto> mesDeviceTreeDtos) { List<MesDeviceTreeDto> childrenList = mesDeviceTreeDtos.stream().filter(e -> Objects.equals(e.getPId(), root.getId())).map( e -> { e.setChildren(getChildrens(e, mesDeviceTreeDtos)); return e; } ).collect(Collectors.toList()); return childrenList; }