简体   繁体   中英

Java: Comparing two collections for new or updated objects

I have two Collections or Arraylists of possibly unequal sizes that will need to be compared. One Collection is a newly downloaded Collection of objects from a REST payload. Another is a Collection from a local repository of Collection of objects. Neither of the Collections will have duplicate objects.

The idea is to find the new objects which doesn't exist in the local repository or objects which have been updated in the downloaded collection from the existing objects in the local repository. Thereby, the class will eventually have two methods to return a Collection of new objects and updated objects

Signature of an object consists of:

membershipObject:
                id
                start_date
                end_date
                uniqueId

id and uniqueId are unique in the collection that makes it ideal to compare them. start_date wouldn't usually change, but end_date can be null or have a datetime object. I have a support method to find if an Object is "active" or "inactive" depending on whether end_date is null or not.

And object is considered updated if the end_date has changed since my last download.

Eg:

downloadedCollection
    0:
      id: 1
      start_date: 2017-05-01 00:00:00
      end_date: null
      uniqueId: <unique-string-abc>
    1:
      id: 2
      start_date: 2017-04-01 00:00:00
      end_date: 2017-05-02 00:00:00
      uniqueId: <unique-string-cde>
    2:
      id: 3
      start_date: 2017-05-01 10:00:00
      end_date: null
      uniqueId: <unique-string-def>

localCollection
    0:
      id: 1
      start_date: 2017-05-01 00:00:00
      end_date: null
      uniqueId: <unique-string-abc>
    1:
      id: 2
      start_date: 2017-04-01 00:00:00
      end_date: null
      uniqueId: <unique-string-cde>

In the above example, id 2 has been updated and id 3 is new from the downloadedCollection .

What is the ideal Java way to compare these two collections considering the complexity of the operation? Java SDK 7.

Have an hash table maintain the id(key) and expiry info(value) available @ local. Whenever you receive new valves loop through them and update ur repository and hash table. This will run O(n), where n is the noof items in the new list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM