title: Cartesian product using Java Streams
body: <p>I have a cartesian product function in JavaScript:</p>
  
  <pre><code>function cartesianProduct(arr) {
      return arr.reduce(function(a,b) {
          return a.map(function(x) {
              return b.map(function(y) {
                  return x.concat(y);
              });
          }).reduce(function(a,b) { return a.concat(b); }, []);
      }, [[]]);
  }
  </code></pre>
  
  <p>So that if I have a 3D array:</p>
  
  <pre><code>var data = [[['D']], [['E'],['L','M','N']]];
  </code></pre>
  
  <p>The result of <code>cartesianProduct(data)</code> would be the 2D array:</p>
  
  <pre><code>[['D','E'], ['D','L','M','N']]
  </code></pre>
  
  <p><strong>What I'm trying to do is write this cartesian product function in Java using Streams.</strong></p>
  
  <p>So far I have the following in Java:</p>
  
  <pre><code>public Collection&lt;Collection&lt;String&gt;&gt; cartesianProduct(Collection&lt;Collection&lt;Collection&lt;String&gt;&gt;&gt; arr) {
  
      return arr.stream().reduce(new ArrayList&lt;Collection&lt;String&gt;&gt;(), (a, b) -&gt; {
          return a.stream().map(x -&gt; {
              return b.stream().map(y -&gt; {
                  return Stream.concat(x.stream(), y.stream());
              });
          }).reduce(new ArrayList&lt;String&gt;(), (c, d) -&gt; {
              return Stream.concat(c, d);
          });
      });
  }
  </code></pre>
  
  <p>I have a type checking error that states:</p>
  
  <blockquote>
    <p><code>ArrayList&lt;String&gt;</code> is not compatible with <code>Stream&lt;Stream&lt;String&gt;&gt;</code></p>
  </blockquote>
  
  <p>My guesses as to what is wrong:</p>
  
  <ul>
  <li>I need to use a collector somewhere (maybe after the <code>Stream.concat</code>)</li>
  <li>The data type for the identity is wrong</li>
  </ul>