Is there any standard Java library class to represent a tree in Java?
Specifically I need to represent the following:
I wrote a small "TreeMap" class based on "HashMap" that supports adding paths:
import java.util.HashMap;
import java.util.LinkedList;
public class TreeMap extends LinkedHashMap> {
public void put(T[] path) {
LinkedList list = new LinkedList<>();
for (T key : path) {
list.add(key);
}
return put(list);
}
public void put(LinkedList path) {
if (path.isEmpty()) {
return;
}
T key = path.removeFirst();
TreeMap val = get(key);
if (val == null) {
val = new TreeMap<>();
put(key, val);
}
val.put(path);
}
}
It can be use to store a Tree of things of type "T" (generic), but does not (yet) support storing extra data in it's nodes. If you have a file like this:
root, child 1
root, child 1, child 1a
root, child 1, child 1b
root, child 2
root, child 3, child 3a
Then you can make it a tree by executing:
TreeMap root = new TreeMap<>();
Scanner scanner = new Scanner(new File("input.txt"));
while (scanner.hasNextLine()) {
root.put(scanner.nextLine().split(", "));
}
And you will get a nice tree. It should be easy to adapt to your needs.