title: Single-iteration over hierarchy in Java 8
body: <p>How can I implement single-loop iteration over a hierarchy of different objects?</p>
  
  <p><em>(I have used for-loops but these represent a different areas of a grid -- I can barely follow all the values used for positioning. Using a single loop would drastically simplify things.)</em></p>
  
  <p>This hierarchy of objects is what I have....</p>
  
  <pre><code>class Hierarchical &lt; PT extends Hierarchical&lt;?,?,?&gt;,T,CT extends Hierarchical&lt; ?, ?, ? &gt;&gt;{
      ObservableList&lt; Hierarchical &gt; children;  //Zero or more objects..
  }
  
  class Seed   extends Hierarchical { /* never has children-objects */ }
  class Tree   extends Hierarchical { ... }
  class Planet extends Hierarchical { ... }
  </code></pre>
  
  <p><strong>Edit</strong>: Children in the Planet instance are Trees, same for Trees containing Seeds.</p>
  
  <p>...and this is what I want to do:</p>
  
  <pre><code>Planet p = new Planet(); //trees/seeds are instantiated internally.
  Iterator&lt; ? &gt; itr = p.getChildren().iterator();
  while ( itr.hasNext() ) {
      Object obj = itr.next();
      if ( obj instanceof Planet ){ /* cast to Planet &amp; do stuff */ }
      if ( obj instanceof Tree   ){ /* cast to Tree   &amp; do stuff */ }
      if ( obj instanceof Seed   ){ /* cast to Seed   &amp; do stuff */ }
  }
  </code></pre>
  
  <p>Clearly the answer lies in <code>Iterator&lt; ? &gt; itr = p.getChildren().iterator();
  </code> but how can it be implemented? It would seem that every level of the hierarchy would need to keep a position of it's children in the event its children start looping through their children. It's been far too long, I'm not familiar with design-patterns &amp; java's collections anymore.  :(</p>
  
  <p>I'll note that I had an error when trying to use <code>Iterator&lt; Hierarchical &gt; itr = p.getChildren().iterator();</code> because p is of type Planet.</p>
  
  <p><strong>Edit</strong>: This needs to be "Depth-Last" (...or FIFO?). The looping is to simplify generation of the UI so the order is important.</p>