美文网首页
构建Tree工具类

构建Tree工具类

作者: _郑_ | 来源:发表于2021-06-25 12:01 被阅读0次
public static void main(String[] args) {
    List<String> list = new ArrayList<>();
    list.add("/");
    list.add("/java");
    list.add("/java/source/ArrayList");
    list.add("/javascript");

    Iterator<String> iterator = list.iterator();
    Path root = toTree(iterator);
    System.out.println(JSON.toJSONString(root.getChildren(), SerializerFeature.PrettyFormat));
}

static Path toTree(Iterator<String> iterator) {
    Path root = new Path("", new ArrayList<>(), new HashMap<>());
    while (iterator.hasNext()) {
        String next = iterator.next();
        String[] arr = next.split("/");
        Path parent = root;
        Map<String, Path> map = parent.getChildrenMap();
        for (int i = 1, len = arr.length; i < len; i++) {
            String p = arr[i];
            Path path = map.get(p);
            if (path != null) {
                parent = path;
                continue;
            }
            path = new Path(p, new ArrayList<>(), new HashMap<>());
            parent.getChildren().add(path);
            parent.getChildrenMap().put(p, path);
            parent = path;
        }
    }
    return root;
}

@Data
@NoArgsConstructor
@AllArgsConstructor
static class Path {
    private String name;
    private List<Path> children;
    @JsonIgnore
    private Map<String, Path> childrenMap;
}

相关文章

网友评论

      本文标题:构建Tree工具类

      本文链接:https://www.haomeiwen.com/subject/odznyltx.html