title: Iteratively compute the Cartesian product of an arbitrary number of sets
body: <p>I want to compute the cartesian product of an arbitrary number of <strong>nonempty</strong> sets in Java.</p>
  
  <p>I've wrote that iterative code...</p>
  
  <pre><code>public static &lt;T&gt; List&lt;Set&lt;T&gt;&gt; cartesianProduct(List&lt;Set&lt;T&gt;&gt; list) {
      List&lt;Iterator&lt;T&gt;&gt; iterators = new ArrayList&lt;Iterator&lt;T&gt;&gt;(list.size());
      List&lt;T&gt; elements = new ArrayList&lt;T&gt;(list.size());
      List&lt;Set&lt;T&gt;&gt; toRet = new ArrayList&lt;Set&lt;T&gt;&gt;();
      for (int i = 0; i &lt; list.size(); i++) {
          iterators.add(list.get(i).iterator());
          elements.add(iterators.get(i).next());
      }
      for (int j = 1; j &gt;= 0;) {
          toRet.add(Sets.newHashSet(elements));
          for (j = iterators.size()-1; j &gt;= 0 &amp;&amp; !iterators.get(j).hasNext(); j--) {
              iterators.set(j, list.get(j).iterator());
              elements.set(j, iterators.get(j).next());
          }
          elements.set(Math.abs(j), iterators.get(Math.abs(j)).next());
      }
      return toRet;
  }
  </code></pre>
  
  <p>...but I found it rather inelegant. 
  Someone has a better, still iterative solution? A solution that uses some wonderful functional-like approach?
  Otherwise... suggestion about how to improve it? Errors?</p>