Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating a List<MyClass> collection based on a new List<MyClass> collection

I need to update a List collection with a new List collection in a way that:

  • the original List gets the new items from the new List
  • the items on the original List which are not on the new List get deleted

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:

enter image description here

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...

like image 347
Crocodile Avatar asked Dec 21 '25 16:12

Crocodile


1 Answers

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);
like image 171
Lone nebula Avatar answered Dec 23 '25 05:12

Lone nebula



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!