try this.
static void add(TreeItem<String> node, String path) {
String[] items = path.substring(1).split("/");
for (int i = 0; i < items.length; ++i) {
TreeItem<String> found = null;
for (TreeItem<String> child : node.getChildren())
if (child.getValue().equals(items[i])) {
found = child;
break;
}
if (found == null) {
found = new TreeItem<>(items[i]);
node.getChildren().add(found);
}
node = found;
}
}
static void print(TreeItem<String> node, String indent) {
System.out.printf("%sTreeItem: %s%n", indent, node.getValue());
for (TreeItem<String> child : node.getChildren())
print(child, indent + " ");
}
and
String[] paths = {
"/applications/HI",
"/applications/HI/Hey.txt",
"/applications/HI/Milk",
"/applications/HI/Milk/blah",
"/applications/HI/Milk/HEADIAJQ/text.txt",
"/applications/HI/Milk/HEADIAJQ/thisworks!!!!.txt",
"/applications/HI/MilkiM/TRASHINGTHINGS.txt",
"/applications/HI/emoji.txt",
"/applications/Test",
"/applications/Test/Tjinsg",
};
TreeItem<String> root = new TreeItem<>("root");
for (String path : paths)
add(root, path);
print(root, "");
result:
TreeItem: root
TreeItem: applications
TreeItem: HI
TreeItem: Hey.txt
TreeItem: Milk
TreeItem: blah
TreeItem: HEADIAJQ
TreeItem: text.txt
TreeItem: thisworks!!!!.txt
TreeItem: MilkiM
TreeItem: TRASHINGTHINGS.txt
TreeItem: emoji.txt
TreeItem: Test
TreeItem: Tjinsg
String[]and then convert that back to a hierarchical structure. This is an X-Y problem