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;
}
网友评论