title: Should I use Java 8 Streams Api to combine two Collections?
body: <p>I have this situation where it seems that the Java 8 Streams API would be helpful, but I'm not fully sure how it could be.</p>
  
  <p>From two Collections with distinct element types, I want to build a third collection whose elements are all the possible <em>Pairs</em> of elements from both collections. Basically:</p>
  
  <p>The two distinct element types...</p>
  
  <pre><code>public class A {}
  public class B {}
  </code></pre>
  
  <p>A "pair" of As and Bs.</p>
  
  <pre><code>public class Pair {
     private A a;
     private B b;
  
     public Pair(A a, B b){
       this a = a;
       this b = b;
     }
  }
  </code></pre>
  
  <p>The "<em>combination</em>" made using old-style <code>java.util.Collection</code> API:</p>
  
  <pre><code> public Collection&lt;Pair&gt; combine(Collection&lt;A&gt; as, Collection&lt;B&gt; bs){
      Collection&lt;Pair&gt; pairs = new ArrayList();
      foreach(A a: as){
        foreach(B b: bs){
            Pair pair = new Pair(a,b);
            pairs.add(pair);
        }
      }
      return pairs;
   }
  </code></pre>
  
  <p>The ordering in the resulting pairs collection is not important. So, every instance of Pair could be created and added to the resulting collection in parallel. How could I achieve this?</p>
  
  <p>The best I could figure out by myself was to use the Streams version of <code>foreach</code>:</p>
  
  <pre><code>as.foreach(
    a -&gt; {
      bs.foreach(
        b -&gt; {
            Pair pair = new Pair(a,b);
            pairs.add(pair);
        }
    }
  );
  </code></pre>
  
  <p>This example was made trivial for the sake of simplification. The class <code>Pair</code> is an example of processing two elements into a third one (that is, a <code>java.util.function.BiFunction</code>), and adding them to a <code>Collection</code> is just an example of a mutable reduction.</p>
  
  <p>Is there a more elegant way to do that? Or preferable, in a more profitable way in regards to efficiency? Something like</p>
  
  <pre><code>BiFunction&lt;A,B,Pair&gt; combinator = Pair::new; //or any other function f(a,b)=c;
  
  Stream&lt;Pair&gt; pairStream = 
    Streams.unknownElegantMethod(as.stream(), bs.stream(), combinator);
  </code></pre>