How Best to Compare Two Collections in Java and Act on Them?

前端 未结 8 2195
生来不讨喜
生来不讨喜 2020-12-03 00:41

I have two collections of the same object, Collection oldSet and Collection newSet. The required logic is as follow:

8条回答
  •  感动是毒
    2020-12-03 01:17

    I'd move to lists and solve it this way:

    1. Sort both lists by id ascending using custom Comparator if objects in lists aren't Comparable
    2. Iterate over elements in both lists like in merge phase in merge sort algorithm, but instead of merging lists, you check your logic.

    The code would be more or less like this:

    /* Main method */
    private void execute(Collection oldSet, Collection newSet) {
      List oldList = asSortedList(oldSet);
      List newList = asSortedList(newSet);
    
      int oldIndex = 0;
      int newIndex = 0;
      // Iterate over both collections but not always in the same pace
      while( oldIndex < oldList.size() 
          && newIndex < newIndex.size())  {
        Foo oldObject = oldList.get(oldIndex);
        Foo newObject = newList.get(newIndex);
    
        // Your logic here
        if(oldObject.getId() < newObject.getId()) {
          doRemove(oldObject);
          oldIndex++;
        } else if( oldObject.getId() > newObject.getId() ) {
          doAdd(newObject);
          newIndex++;
        } else if( oldObject.getId() == newObject.getId() 
                && isModified(oldObject, newObject) ) {
          doUpdate(oldObject, newObject);
          oldIndex++;
          newIndex++;
        } else {
          ... 
        }
      }// while
    
      // Check if there are any objects left in *oldList* or *newList*
    
      for(; oldIndex < oldList.size(); oldIndex++ ) {
        doRemove( oldList.get(oldIndex) );  
      }// for( oldIndex )
    
      for(; newIndex < newList.size(); newIndex++ ) {
        doAdd( newList.get(newIndex) );
      }// for( newIndex ) 
    }// execute( oldSet, newSet )
    
    /** Create sorted list from collection 
        If you actually perform any actions on input collections than you should 
        always return new instance of list to keep algorithm simple.
    */
    private List asSortedList(Collection data) {
      List resultList;
      if(data instanceof List) {
         resultList = (List)data;
      } else {
         resultList = new ArrayList(data);
      }
      Collections.sort(resultList)
      return resultList;
    }
    

提交回复
热议问题