title: Java8 Streaming a class hierarchy
body: <p>I am slowly learning the new Java 8 features and I am trying to find a way to process a class hierarchy (from child to parent) as a stream.</p>
  
  <p>For instance find an annotation on a class or it's parents.</p>
  
  <p>Before Java 8, I would have done it this way :</p>
  
  <pre><code>public static &lt;T extends Annotation&gt; T getAnnonationOn(Class&lt;?&gt; type, Class&lt;T&gt; annType) {
      Class&lt;?&gt; t = type;
      T annot = null;
      while (t != null &amp;&amp; annot == null) {
          annot = t.getAnnotation(annType);
          t = t.getSuperclass();
      }
      return annot;
  }
  </code></pre>
  
  <p>Now I wish to do it with a more "functional programming" way.
  I could not find a better way than concatenate streams with a recursive like follow :</p>
  
  <pre><code>import java.lang.annotation.Annotation;
  import java.util.stream.Stream;
  
  public static &lt;T extends Annotation&gt; T getAnnonationOn(Class&lt;?&gt; type, Class&lt;T&gt; annType) {
      return ClassIterator.streamSuperclass(type)
          .map(t -&gt; t.getAnnotation(annType))
          .filter(a -&gt; a != null)
          .findFirst()
          .orElse(null);
  }
  
  public static class ClassIterator {
      public static Stream&lt;Class&lt;?&gt;&gt; streamSuperclass(Class&lt;?&gt; type) {
          if (type.getSuperclass() != null) {
              return Stream.concat(Stream.of(type), Stream.of(type.getSuperclass()).flatMap(ClassIterator::streamSuperclass));
          }
          return Stream.of(type);
      }
  }
  </code></pre>
  
  <p>But I am not quite satisfied of the solution. Although I did not benchmark it I think the stream concatenation is quite cumbersome and under performant.</p>
  
  <p>Is there a better way to turn a recursive into a stream ?</p>