树形结构和普通list数据的互换

树形结构和普通list数据的互换

1. list转树形结构

 /**
     * list转树形List
     * @param list
     * @return
     */
    public static List<RetTreePath> list2tree(List<RetTreePath> list) {
        List<RetTreePath> result = new ArrayList<>();

        Map<Long, RetTreePath> map = list.stream().collect(Collectors.toMap(test -> test.getId(), test -> test));
        for (RetTreePath test : list) {
            RetTreePath p = map.get(test.getParentId());
            if (p == null) {
                result.add(test);
            } else {
                if (p.getChildren() == null) {
                    p.setChildren(new ArrayList<>());
                }
                p.getChildren().add(test);
            }
        }
        return result;
    }

二. 树形结构转list
 /**
     * 树形list转list
     * @param list
     * @return
     */
    public static List<RetTreePath> tree2list(List<RetTreePath> list) {
        List<RetTreePath> result = new ArrayList<>();
        for (RetTreePath retTreePath : list) {
            List<RetTreePath> c = retTreePath.getChildren();
            result.add(retTreePath);
            if (!CollectionUtils.isEmpty(c)) {
                result.addAll(tree2list(c));
                retTreePath.setChildren(null);//
            }
        }
        return result;
    }

你可能感兴趣的:(Java开发技术要点,树形结构和list的互转)