title: Replace nested for loops with parallel stream - Java
body: <p>I'm working on improving the speed of a program where performance is critical. Currently it fails to process large data sets. There are many nested for loops and so I thought it would be worth trying parallel streams. I have access to a high performance cluster so potentially have many cores available.
  I have the method below:</p>
  
  <pre><code>public MinSpecSetFamily getMinDomSpecSets() {
          MinSpecSetFamily result = new MinSpecSetFamily();
          ResourceType minRT = this.getFirstEssentialResourceType();
          if (minRT == null || minRT.noSpecies()) {
              System.out.println("Problem in getMinDomSpecSets()");
          }
          for (Species spec : minRT.specList) {
              SpecTree minTree = this.getMinimalConstSpecTreeRootedAt(spec);
              ArrayList&lt;SpecTreeNode&gt; leafList = minTree.getLeaves();
              for (SpecTreeNode leaf : leafList) {
                  ArrayList&lt;Species&gt; sp = leaf.getAncestors();
                  SpecSet tmpSet = new SpecSet(sp);
                  result.addSpecSet(tmpSet);
              }
          }
          return result;
      }
  </code></pre>
  
  <p>I understand that I can turn a nested for loop into a parallel stream with something like:</p>
  
  <pre><code>minRT.specList.parallelStream().flatMap(leaf -&gt; leaflist.parallelStream())
  </code></pre>
  
  <p>However, I cannot find examples showing how to deal with the actions inside each for loop and I'm not at all confident about how this is supposed to work. I'd really appreciate some assistance and explanation of how to convert this method so that I can translate the solution to other methods in the program too.
  Thanks.</p>