Note that there are some explanatory texts on larger screens.

plurals
  1. POHow Best to Compare Two Collections in Java and Act on Them?
    primarykey
    data
    text
    <p>I have two collections of the same object, <code>Collection&lt;Foo&gt; oldSet</code> and <code>Collection&lt;Foo&gt; newSet</code>. The required logic is as follow:</p> <ul> <li>if <code>foo</code> is in(*) <code>oldSet</code> but not <code>newSet</code>, call <code>doRemove(foo)</code></li> <li>else if <code>foo</code> is not in <code>oldSet</code> but in <code>newSet</code>, call <code>doAdd(foo)</code></li> <li>else if <code>foo</code> is in both collections but modified, call <code>doUpdate(oldFoo, newFoo)</code></li> <li>else if <code>!foo.activated &amp;&amp; foo.startDate &gt;= now</code>, call <code>doStart(foo)</code></li> <li>else if <code>foo.activated &amp;&amp; foo.endDate &lt;= now</code>, call <code>doEnd(foo)</code></li> </ul> <p>(*) "in" means the unique identifier matches, not necessarily the content.</p> <p>The current (legacy) code does many comparisons to figure out <code>removeSet</code>, <code>addSet</code>, <code>updateSet</code>, <code>startSet</code> and <code>endSet</code>, and then loop to act on each item.</p> <p>The code is quite messy (partly because I have left out some spaghetti logic already) and I am trying to refactor it. Some more background info:</p> <ul> <li>As far as I know, the <code>oldSet</code> and <code>newSet</code> are actually backed by <code>ArrayList</code></li> <li>Each set contains less than 100 items, most likely max out at 20</li> <li>This code is called frequently (measured in millions/day), although the sets seldom differ</li> </ul> <p>My questions:</p> <ul> <li>If I convert <code>oldSet</code> and <code>newSet</code> into <code>HashMap&lt;Foo&gt;</code> (order is not of concern here), with the IDs as keys, would it made the code easier to read and easier to compare? How much of time &amp; memory performance is loss on the conversion?</li> <li>Would iterating the two sets and perform the appropriate operation be more efficient and concise?</li> </ul>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload