Note that there are some explanatory texts on larger screens.

plurals
  1. POUpdating a List<MyClass> collection based on a new List<MyClass> collection
    primarykey
    data
    text
    <p>I need to update a List collection with a new List collection in a way that:</p> <ul> <li>the original List gets the new items from the new List</li> <li>the items on the original List which are not on the new List get deleted</li> </ul> <p>Unfortunately, clearing the original List and rebuilding it from the new one is not an option because those already hold objects with important values/references I do not want to lose. </p> <p>What I need to achieve can be summarized as follows:</p> <p><img src="https://i.stack.imgur.com/NmlKA.png" alt="enter image description here"></p> <p>I came up with 'some' solution which 'kind of' works, but I really don't like it and I am not sure how efficient this is... </p> <pre><code>class MyClass{ int someInt; String someString; int rowID; // DB reference, cannot lose it... ... } public static List&lt;MyClass&gt; mergeMyClassLists(List&lt;MyClass&gt; origList, List&lt;MyClass&gt; newList){ Integer index[]= new Integer[origList.size()]; // Find the ones to remove from the old list int c=0; for(MyClass origMyClass:origList){ if(!hasMyClass(newList,origMyClass)) index[c] = origList.indexOf(origMyClass); c++; } // Then remove them for(int i:index){ if(index[i]!=null) origList.remove(index[i]); } //Add new ones for(MyClass newMyClass:newList){ if(!hasMyClass(origList,newMyClass)) origList.add(newMyClass); } return origList; } private static boolean hasMyClass(List&lt;MyClass&gt; myClassList, MyClass myClass){ for(MyClass mc:myClassList){ // Are they the same? based on my own criteria here if(mc.someInt == myClass.someInt &amp;&amp; mc.someString.equals(myClass.someString)) return true; } return false; } </code></pre> <p><strong>Is there a better/standard way of doing this?</strong> I get the feeling I might be over-complicating the situation...</p>
    singulars
    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