title: Working with a stream of streams
body: <p>I want to work out if I can do something like this. Suppose I have a stream of the numbers 1 - 20. I want to utilise a feature such as a drop 3 (limit or skip I guess in Java terms?) and produce a stream of streams that is the numbers:</p>
  
  <p>1 - 20, 4 - 20, 7- 20, etc</p>
  
  <p>then possibly flat map these alll into one stream. I've tried various combinations of using Stream.iterate primarily to generate streams from streams, but I keep geting an IllegalStateException saying the stream has already operated upon or closed.</p>
  
  <p>For example one may expect this code:</p>
  
  <pre><code>  Stream.iterate(Stream.of(1,2,3,4,5), x -&gt; x.skip(1).collect(Collectors.toList()).stream()).limit(5).flatMap(x -&gt; x).forEach(x -&gt; System.out.println(x));
  </code></pre>
  
  <p>To produce: 1,2,3,4,5,2,3,4,5,3,4,5,4,5,5</p>
  
  <p>But it doesn't, it throws an exception. Am I missing something obvious here. I know of a takeWhile operation but don't think it's out until Java 9.</p>
  
  <p>EDIT: I have managed to get an ugly solution to what I was trying to achieve using the following:</p>
  
  <pre><code>List&lt;Integer&gt; list = IntStream.rangeClosed(1, 20).boxed().collect(Collectors.toList());
  Stream.iterate(list, x -&gt; x.stream().skip(3).collect(Collectors.toList())).limit(7).map(x -&gt; x.stream().limit(3).collect(Collectors.toList())).flatMap(List::stream).forEach(System.out::println);
  </code></pre>
  
  <p>So I have a list 1..20, then end up with a stream of lists 1..20, 4..20, 7..20, etc. If I then take the first 3 elements of each of these I end up with 1..3, 4..6, 7..9, etc. If I flatMap this, I get back to 1..20.</p>
  
  <p>My question is, A. is there a way for me to not have to hardcode limit(7) above, so it automatically stops when I've processed all of the input element set, and B. I don't like having to collect into lists - can I not do this purely with streams prior to a collection at the end or even just printing after a flat map?</p>