JDK8 组装成树
1.返回的结果集
@Data public class TreeDeviceDTO { /** * 节点id */ private String id; /** * 节点名称 */ private String name; /** * 父节点 */ private String parentId; /** * 层级 * */ private Integer level; }
2,定义全局的变量 来封装层级
private List<TreeDeviceDTO> rootList; // 根节点对象存放到这里 private List<TreeDeviceDTO> bodyList; // 其他节点存放到这里,可以包含根节点 (我放的是2,3级的节点) public JtlCompanyGradeServiceImpl(List<TreeDeviceDTO> rootList, List<TreeDeviceDTO> bodyList) { this.rootList = rootList; this.bodyList = bodyList; }
rootList 和 bodyList 封装好了
直接调用下边这个方法 组成树
public List<TreeDeviceDTO> getTree() { //调用的方法入口 if (CollectionUtils.isNotEmpty(bodyList) && CollectionUtils.isNotEmpty(bodyList)) { //声明一个map,用来过滤已操作过的数据 Map<String, String> map = Maps.newHashMapWithExpectedSize(bodyList.size()); rootList.forEach(beanTree -> getChild(beanTree, map)); return rootList; } return null; } public void getChild(TreeDeviceDTO beanTree, Map<String, String> map) { List<TreeDeviceDTO> childList = Lists.newArrayList(); bodyList.stream().filter(c -> !map.containsKey(c.getId())).filter(c -> c.getParentId().equals(beanTree.getId())) .forEach(c -> { map.put(c.getId(), c.getParentId()); getChild(c, map); childList.add(c); }); beanTree.setChildTreeDto(childList); }