title: Java 8 Stream, getting head and tail
body: <p>Java 8 introduced a <a href="http://download.java.net/jdk8/docs/api/java/util/stream/Stream.html">Stream</a> class that resembles Scala's <a href="http://www.scala-lang.org/files/archive/nightly/docs/library/scala/collection/immutable/Stream.html">Stream</a>, a powerful lazy construct using which it is possible to do something like this very concisely:</p>
  
  <pre class="lang-scala prettyprint-override"><code>def from(n: Int): Stream[Int] = n #:: from(n+1)
  
  def sieve(s: Stream[Int]): Stream[Int] = {
    s.head #:: sieve(s.tail filter (_ % s.head != 0))
  }
  
  val primes = sieve(from(2))
  
  primes takeWhile(_ &lt; 1000) print  // prints all primes less than 1000
  </code></pre>
  
  <p>I wondered if it is possible to do this in Java 8, so I wrote something like this:</p>
  
  <pre class="lang-java prettyprint-override"><code>IntStream from(int n) {
      return IntStream.iterate(n, m -&gt; m + 1);
  }
  
  IntStream sieve(IntStream s) {
      int head = s.findFirst().getAsInt();
      return IntStream.concat(IntStream.of(head), sieve(s.skip(1).filter(n -&gt; n % head != 0)));
  }
  
  IntStream primes = sieve(from(2));
  </code></pre>
  
  <p>Fairly simple, but it produces <code>java.lang.IllegalStateException: stream has already been operated upon or closed</code> because both <code>findFirst()</code> and <code>skip()</code> are terminal operations on <code>Stream</code> which can be done only once.</p>
  
  <p>I don't really have to use up the stream twice since all I need is the first number in the stream and the rest as another stream, i.e. equivalent of Scala's <code>Stream.head</code> and <code>Stream.tail</code>. Is there a method in Java 8 <code>Stream</code> that I can use to achieve this?</p>
  
  <p>Thanks.</p>