Beware, it is not a binary tree
- Simple
- Iterable
- Modification: mapping, filtering, sorting
- Pretty-printing
- Different traversals - depth-first, breadth-first
<dependency>
<groupId>org.jkee.gtree</groupId>
<artifactId>gtree</artifactId>
<version>0.64</version>
</dependency>- Key builder
- Path builder
Assume you have objects like:
public class Entity {
public final int id;
public final int parentId;
...
}And assume that id == 0 means no parent (e.g. root).
KeyTreeBuilder will be the right choice.
-
Create a
Funnel.Funnelis an object which knows how to extractidandparentIdfrom your object.KeyTreeBuilder.Funnel<Integer, Entity> funnel = new KeyTreeBuilder.Funnel<Integer, Entity>() { @Override public Integer getKey(Entity node) { return node.id; } @Override public Integer getParentKey(Entity node) { //so lets take 0 as no parent if (node.parentId == 0) return null; return node.parentId; } };
-
Create a
KeyTreeBuilder. Builder is stateless so you can create only one.KeyTreeBuilder<Integer, Entity> builder = new KeyTreeBuilder<Integer, Entity>(funnel);
-
Build a tree!
Tree<Entity> tree = builder.buildTree(entities);
If you want a forest, or an Integer -> Tree<Entity> mapping, you can use .build method and get more results.
Full example available here
Assume you have a batch of url and you want to build a tree structure. It's simple, really.
All we need is the PathTreeBuilder.
-
Create a
Funnelwhich knows how to extract a path from your object. In case of URL it will be a split by/(simplistically).PathTreeBuilder.Funnel<String, String> urlFunnel = new PathTreeBuilder.Funnel<String, String>() { @Override public List<String> getPath(String value) { return Lists.newArrayList(value.split("/")); } };
-
Create a
PathTreeBuilder. Also stateless.PathTreeBuilder<String, String> builder = new PathTreeBuilder<String, String>(urlFunnel);
-
Build a tree! Actually, not a tree - a forest. There are no guarantees of root uniqueness.
List<Tree<String>> build = builder.build(urls);
Full example available here