非递归实现集合与树的转换

在实际的开发过程中时常需要将树型结构数据转换为普通集合或者将普通集合转换成树形结构数据,除了递归之外的转换方法

  • TestDto.java
public class TestDto {
    private int id;
    private List childrens;
    private int parentId;

    public TestDto(int id, int parentId) {
        this.id = id;
        this.parentId = parentId;
    }
}
  • 普通数组转树形数组
    public List toTree(List lists) {
        for (TestDto dto : lists) {
            final int id = dto.getId();
            List childrens = dto.getChildrens();
            if (childrens == null) {
                childrens = new ArrayList<>();
            }
            for (TestDto test : lists) {
                if (test.getParentId() == id) {
                    childrens.add(test);
                }
            }
            dto.setChildrens(childrens);
        }
        for (int i = 0; i < lists.size(); i++) {
            final TestDto testDt = lists.get(i);
            if (testDt.getParentId() != 0) {
                lists.remove(testDt);
                i--;
            }
        }
        return lists;
    }
  • 树形数组转普通数组
    public List treeToList(List lists) {
        List testDtoList = Lists.newArrayList();

        for (int i = 0; i < lists.size(); i++) {
            TestDto elementAt = lists.get(i);
            testDtoList.add(elementAt);
            final List childrens = elementAt.getChildrens();
            if (CollectionUtils.isNotEmpty(childrens)) {
                lists.addAll(childrens);
            }
        }
        return testDtoList;
    }
       

你可能感兴趣的:(非递归实现集合与树的转换)