title: Nested for-each on same list in Java?
body: <p>I have a list of lists of Integer that I'm using to build chains based on an input file. The input specifies pairs (e.g. "3, 1" indicates that 1 replaces 3 in the application), and there are overlaps in the pairs (e.g. "3, 1" and "1, 4" would mean that 1 replaces 3 and 4 replaces 1, so ultimately, 4 replaces 3).</p>
  
  <p>In order to reduce all of the pairs into their final chains, I have a list containing lists of all the pairs, and then I find which entries in the list overlap and append to the chains as needed, removing the pair that has been appended to another. This is how I am attempting to do this, but I know the failure is in doubling up the iterator references:</p>
  
  <pre><code>    for (ArrayList&lt;Integer&gt; outerChain : chains) {
          for (ArrayList&lt;Integer&gt; innerChain : chains) {
              if (outerChain.get(0).equals(innerChain.get(innerChain.size() - 1))) {
                  outerChain.remove(0);
                  innerChain.addAll(outerChain);
                  chains.remove(outerChain);
                  break;
              }
          }
      }
  </code></pre>
  
  <p>As an example of the input/desired output from this operation:</p>
  
  <pre><code>    {&lt;1,3&gt;,&lt;2,7&gt;,&lt;7,9&gt;,&lt;8,12&gt;,&lt;9,1&gt;,&lt;6,8&gt;}
  </code></pre>
  
  <p>being individual lists corresponding to input pairs, the output would be:</p>
  
  <pre><code>    {&lt;2,7,9,1,3&gt;,&lt;6,8,12&gt;}
  </code></pre>
  
  <p>Is there a way I can nest iterators like this such that the references within each iterator are updated when removing or updating for one or the other?</p>
  
  <p>Thanks in advance for the help!</p>