title: Merge sets when two elements in common
body: <p>This is the follow up of <a href="https://stackoverflow.com/questions/34963632/compare-sets-inside-a-set#comment57665618_34964554">compare sets</a></p>
  
  <p>I have </p>
  
  <pre><code>Set&lt;Set&lt;Node&gt;&gt; NestedSet = new HashSet&lt;Set&lt;Node&gt;&gt;();
  
  [[Node[0], Node[1], Node[2]], [Node[0], Node[2], Node[6]], [Node[3], Node[4], Node[5]]  [Node[2], Node[6], Node[7]] ]
  </code></pre>
  
  <p>I want to merge the sets when there are two elements in common. For example 0,1,2 and 0,2,6 has two elements in common so merging them to form [0,1,2,6]. </p>
  
  <p>Again [0,1,2,6] and [2,6,7] has 2 and 6 common. so merging them and getting [0,1,2,6,7]. </p>
  
  <p>The final output should be :</p>
  
  <pre><code>[  [Node[0], Node[1], Node[2], Node[6], Node[7]], [Node[3], Node[4], Node[5]] ]
  </code></pre>
  
  <p>I tried  like this :</p>
  
  <pre><code>         for (Set&lt;Node&gt; s1 : NestedSet ) {
                          Optional&lt;Set&lt;Node&gt;&gt; findFirst = result.stream().filter(p -&gt; { HashSet&lt;Node&gt; temp = new HashSet&lt;&gt;(s1); 
                          temp.retainAll(p); 
                          return temp.size() == 2; }).findFirst(); 
  
                          if (findFirst.isPresent()){
  
                              findFirst.get().addAll(s1); 
                          }
                          else {
                              result.add(s1);
                          }    
  
                      }
  </code></pre>
  
  <p>But the result I got was :</p>
  
  <pre><code>[[Node[0], Node[1], Node[2], Node[6], Node[7]], [Node[3], Node[4], Node[5]], [Node[0], Node[2], Node[6], Node[7]]]
  </code></pre>
  
  <p>Any idea ? Is there any way to get the desired output?</p>