title: Difference between 2 lists of objects in Java
body: <p>I have a obj type <code>MyObj</code> as follow:</p>
  
  <pre><code>  class MyObj{
      String id;
      String username;
      String fullName;
      String age;
  
      //getters &amp; setters
  }
  </code></pre>
  
  <p>Suppose we have 2 lists containing different number of elements like so:</p>
  
  <pre><code>List&lt;MyObj&gt; listA
  List&lt;MyObj&gt; listB
  </code></pre>
  
  <p>I have a generic method that detects elements from <code>listA</code> that are missing in <code>listB</code>:</p>
  
  <pre><code> public static &lt;T&gt; List&lt;T&gt; getListDifference(List&lt;T&gt; list1, List&lt;T&gt; list2) {
          Collection&lt;T&gt; first = new HashSet&lt;T&gt;(list1);
          Collection&lt;T&gt; second = new HashSet&lt;T&gt;(list2);
          first.removeAll(second);
          return new ArrayList&lt;T&gt;(first);
      }
  </code></pre>
  
  <p>If objects from <code>listA</code> and <code>listB</code> has the same fields for all items, everything works just fine. </p>
  
  <p>The problem is that some items has only <code>id</code> and <code>username</code> but others can have <code>fullName</code> or <code>age</code> too, and as result this method doesn't work anymore. I'd like to keep the same logic, considering only <code>id</code> field because it's present in all objects.</p>
  
  <p>One obvious method is to copy only object's <code>id</code> field in other <code>List&lt;String&gt;</code> and work with obtained lists to detect elements, then just search for obj from both lists by <code>id</code>. This method has a big complexity, because of multiple iterations. Is there a short way to achieve this?</p>