简体   繁体   中英

Optimized way to check for equality between value of Objects inside a List

I have two lists :
A : List<MyCustomObject>
B. List<MyCustomObject>

MyCustomObject has various fields. For instance a field id

In my program, I need to check if same id exists in both lists. So currently I am doing nested iterations :

for(int i=0;i<a.size();i++) {

   MyCustomObject obj = a.get(i);

   for(int j=0;j<b.size();j++) {

    if( obj.getId().equals(b.get(j).getId()) {

        //do something
        break;
       }
   }
 }

As I frequently need to do this operation, it looks me unoptimized as I am frequently iterating over long lists.

How can I optimize this operation ?

Instead of using a list you could use a Map , for example a HashMap - assuming your id is an int, it could look like:

Map<Integer, MyCustomObject> objects = new HashMap<>();
//populate
objects.put(someCustomObject.getId(), someCustomObject);
//find an id:
CustomObject obj = objects.get(someId);

note: that assumes that the ids are unique.

A linear-time algorithm is to hash the ID values in the first list against a Boolean. Then you travel on the second list to look up the ID values, and if the hash already contains a key of that ID, the ID is shared between the two lists.

You can also improve over the runtime of O(n^2) by sorting the lists by id, which is an O(n log n) operation, and traveling through the lists linearly to see if any of the values are shared. If you want to keep the order of the lists, you could create another, sorted copy of the lists but that would add memory space.

What you've got, I believe, is as good as you can do without changing the order of the list elements or creating a new data structure. I don't know your requirements, though.

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