I need to update a List collection with a new List collection in a way that:
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.
What I need to achieve can be summarized as follows:

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...
class MyClass{
int someInt;
String someString;
int rowID; // DB reference, cannot lose it...
...
}
public static List<MyClass> mergeMyClassLists(List<MyClass> origList, List<MyClass> 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<MyClass> myClassList, MyClass myClass){
for(MyClass mc:myClassList){
// Are they the same? based on my own criteria here
if(mc.someInt == myClass.someInt && mc.someString.equals(myClass.someString)) return true;
}
return false;
}
Is there a better/standard way of doing this? I get the feeling I might be over-complicating the situation...
Override equals and hashCode in MyClass to fit your requirements for equality.
Here is an example:
public boolean equals(Object o) {
if( !(o instanceof MyClass) ) return false;
MyClass mc = (MyClass)o;
if(this.someInt != mc.someInt)
return false;
return (this.someString == null)
? mc.someString == null
: this.someString.equals(mc.someString);
}
public int hashCode() {
int hashCode = someInt;
if(someString != null)
hashCode ^= someString.hashCode();
return hashCode;
}
When you've overridden those, it's as simple as this:
origList.retainAll(newList);
newList.removeAll(origList);
origList.addAll(newList);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With