Java8: find a node in a tree

With Java8 it is now quite easy to search for a node within a tree with less code than in Java7 or older.

We assume, that we have tree with one root node. Each node is identified by an unique id and can have multiple sub-nodes. There are no cycles within this data structure.

Now we want to find node nodeId within this tree. To do so, we can write the following method findNode with Java8:

public class Node {
  private long id; // unique
  private List children; // no cycles
  ...
  public Node findNode(final long nodeId) {
    if (id == nodeId) {
      return this;
    }
    return children.stream()
      .map(node -> node.getNode(nodeId))
      .filter(node -> node != null && node.getId() == nodeId)
      .findAny()
      .orElse(null);
  }
}

Hint: you can speed up the search by using a parallelStream instead of a stream.

For comparison, this is what we had to write in earlier Java versions:

public class Node {
  private long id; // unique
  private List children; // no cycles
  ...
  public Node findNode(final long nodeId) {
    if (id == nodeId) {
      return this;
    }
    Node node = null;
    for (Node n : children) {
      node = n.findNode(nodeId);
      if (node != null) {
        break;
      }
    }
    return node;
  }
}

If you activate these fields by a click, then data will be transmitted to Facebook, Twitter or Google - possibly also to foreign countries and in certain circumstances the data is also saved.

Leave a Reply

Your email address will not be published. Required fields are marked *