Walking the Entity tree

Elliot Ford edited this page May 7, 2015 · 6 revisions

What makes the tree

An EntityContainer can create and store many entities and an Entity is also an EntityContainer. This creates a tree structure that can be traversed using an EntityVisitor.

Creating an EntityVisitor

A visitor will visit each Entity within the tree at each level (breadth) and the returning EntityVisitResult will determine the next action for the walker.

Result states:

  1. EntityVisitResult.CONTUNUE: Continue to process this sub-tree.
  2. EntityVisitResult.EXIT: Exit all sub-trees.
  3. EntityVisitResult.IGNORE_CHILDREN: Make this member a leaf.
  4. EntityVisitResult.IGNORE_SIBLINGS: Only continue this sub-tree.

A visit-all example:

EntityVisitor visitor = e -> {
    System.out.println(e.getID());
    return EntityVisitResult.CONTINUE;
};

Walking the tree

The utility Entities (API docs for Entities) provides methods for walking the entity tree:

EntityContainer container = /* Nice awkward tree */

Entities.walkEntityTree(container, visitor);

Entities.walkEntityTree(container, 2, visitor); // Max depth of 2

The above two methods walk through the tree breadth-first until the tree is either fully traversed or the visitor returns EntityVisitResult.EXIT. For the second example the breath-depth is also a exit qualifying criteria.

EntityContainer container = /* Nice awkward tree */

Stream<Entity> stream = Entities.walkEntities(container);

Stream<Entity> depthExitingStream = Entities.walkEntities(container, 2); // Max depth of 2

The last two methods create a lazy initialised stream of entities by walking the tree (this could be considered a recursive entity stream). Like the first two examples the last example is also breadth-depth exiting.

Utility methods using the Entity walker.

Like the other walking utility methods these are available from Entities (API docs for Entities).

Check if an entity is in the tree: Entities.findEntityRecursively(container, /* Some ID */)

Get the total entity count: Entities.getEntityCountRecursively(container)

Get all the entity IDs: Entities.getEntityIDsRecursively(container)

Potential issues

  • It is worth noting that walking the Entity tree works from the entity that was selected and down so to get the whole tree the top-level entity should be the starting point.
  • Walking the tree while transfers are in progress could yield interesting results in concurrent application.
  • Entity, EntityContainer and EntityFactory can have custom implementations that may allow for infinite loops.
Clone this wiki locally
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.