2

I have a List of n Paths and i want to create a Hierarchy ( Tree structure with objects ) out of them.

E.g. Paths :

/src/main/java/tools/mockfile/generator/data/RecordPart.java
/src/main/java/tools/mockfile/generator/Analyzer.java
/src/main/java/tools/mockfile/test/Menu.java
...

small Hierarchy :

 mockfile
    ├── generator
    │   ├── data
    │   │   └── RecordPart.java
    │   └── Analyzer.java   
    └── test
        ├── Menu.java
        └── ...

Is there any Library or Method who could help me to sort the paths to a hierarchy ? Or is the only way to split the Strings and compare all Parts and build my own Hierarchy?

Drextor
  • 433
  • 1
  • 6
  • 24

2 Answers2

2

You could just use a nested Map as a tree, mapping Strings to other nested Maps. You could define a helper class just to get the type information right:

class Tree extends HashMap<String, Tree> {}
Tree tree = new Tree();

This way, the tree already comes with all the useful functionality it needs. Then, just iterate the paths and their segments and use computeIfAbsent to create new branches as needed:

List<String> paths = Arrays.asList(
        "/src/main/java/tools/mockfile/generator/data/RecordPart.java",
        "/src/main/java/tools/mockfile/generator/Analyzer.java",
        "/src/main/java/tools/mockfile/test/Menu.java");

for (String path : paths) {
    Tree node = tree;
    for (String segment : path.split("/")) {
        node = node.computeIfAbsent(segment, s -> new Tree());
    }
}

Afterwards, the tree looks like this (indentation mine; note that the root is empty string):

 {={src={main={java={tools={mockfile={test={Menu.java={}},
                                      generator={data={RecordPart.java={}}, 
                                                 Analyzer.java={}}}}}}}}}

Alternatively, you could e.g. put null for files (leaves) instead of another empty Tree.

tobias_k
  • 81,265
  • 12
  • 120
  • 179
0

If you desire to create and manipulate tree structure the ad hoc library is Jgrapht.

Denis Ismailovski
  • 311
  • 1
  • 7
  • 15