title: Flatmap nested collection
body: <p>I have a list of objects, some of them can be collections. I would like to get a stream of plain objects.</p>
  
  <pre><code>List&lt;Object&gt; objects = List.of(1, 2, "SomeString", List.of(3, 4, 5, 6), 
      7, List.of("a", "b", "c"),
      List.of(8, List.of(9, List.of(10))));
  </code></pre>
  
  <p>I would like to get a stream with elements.</p>
  
  <pre><code>1, 2, "SomeString", 3, 4, 5, 6, 7, "a", "b", "c", 8, 9, 10
  </code></pre>
  
  <p>I have tried</p>
  
  <pre><code>Function&lt;Object, Stream&lt;Object&gt;&gt; mbjectToStreamMapper = null; //define it. I have not figured it out yet!
  objects.stream().flatMap(ObjectToStreamMapper).forEach(System.out::println);
  </code></pre>
  
  <p>I also checked an <a href="https://www.logicbig.com/how-to/java-8-streams/stream-n-depth-to-flat-collection.html" rel="noreferrer">example</a> which shows how to use a recursive function which flattens a collection. However, in this example <code>.collect(Collectors.toList());</code> used to keep an intermediate result. <code>Collectors.toList()</code> is a terminal operation, which will start processing the stream right away. I would like to get a stream, which I can iterate on later.</p>
  
  <hr>
  
  <h2>Update</h2>
  
  <p>I agree with comments, it is a terrible idea to have a stream composed of objects of different nature. I just wrote this question for simplicity. In real life, it can be that I listen to different events, and process some business objects from incoming streams, some of them can send stream of objects, other - just single objects.</p>