title: Best way to update set of set
body: <p>There is a list of edges connecting the vertices. I'm trying to divide these vertices into groups that are connected to each other.</p>
  <pre><code>static class Edge {
      final String from, to;
  
      Edge(String from, String to) {
          this.from = from;
          this.to = to;
      }
  }
  
  static Set&lt;String&gt; find(String k, Set&lt;Set&lt;String&gt;&gt; sets) {
      for (Set&lt;String&gt; set : sets)
          if (set.contains(k))
              return set;
      return null;
  }
  
  static Set&lt;Set&lt;String&gt;&gt; connectedVertices(List&lt;Edge&gt; edges) {
      Set&lt;Set&lt;String&gt;&gt; result = new HashSet&lt;&gt;();
      for (Edge e : edges) {
          Set&lt;String&gt; from = find(e.from, result);
          Set&lt;String&gt; to = find(e.to, result);
          if (from == null &amp;&amp; to == null) {
              result.add(new HashSet&lt;&gt;(Set.of(e.from, e.to)));
          } else if (from == null) {
              to.add(e.from);
          } else if (to == null) {
              from.add(e.to);
          } else if (from != to) {
              result.remove(to);
              from.addAll(to);
          }
      }
      return result;
  }
  </code></pre>
  <p>And</p>
  <pre><code>    List&lt;Edge&gt; edges = List.of(
          new Edge(&quot;a&quot;, &quot;b&quot;),
          new Edge(&quot;c&quot;, &quot;b&quot;),
          new Edge(&quot;c&quot;, &quot;d&quot;),
          new Edge(&quot;a&quot;, &quot;c&quot;),
          new Edge(&quot;e&quot;, &quot;f&quot;),
          new Edge(&quot;x&quot;, &quot;y&quot;),
          new Edge(&quot;y&quot;, &quot;d&quot;));
      System.out.println(connectedVertices(edges));
  </code></pre>
  <p>But the result is not what I expected.</p>
  <p>Expected:</p>
  <pre><code>[[e, f], [a, b, c, d, x, y]]
  </code></pre>
  <p>Actual:</p>
  <pre><code>[[a, b, c, d, x, y], [a, b, c, d], [e, f]]
  </code></pre>
  <p>I get the results I expect with the following changes, but it's verbose. Is there a better way?</p>
  <pre><code>static Set&lt;Set&lt;String&gt;&gt; connectedVertices(List&lt;Edge&gt; edges) {
      Set&lt;Set&lt;String&gt;&gt; result = new HashSet&lt;&gt;();
      for (Edge e : edges) {
          Set&lt;String&gt; from = find(e.from, result);
          Set&lt;String&gt; to = find(e.to, result);
          if (from == null &amp;&amp; to == null) {
              result.add(new HashSet&lt;&gt;(Set.of(e.from, e.to)));
          } else if (from == null) {
              result.remove(to);
              to.add(e.from);
              result.add(to);
          } else if (to == null) {
              result.remove(from);
              from.add(e.to);
              result.add(from);
          } else if (from != to) {
              result.remove(from);
              result.remove(to);
              from.addAll(to);
              result.add(from);
          }
      }
      return result;
  }
  </code></pre>