简体   繁体   English

检查List内对象值之间相等性的优化方法

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

I have two lists : 我有两个清单:
A : List<MyCustomObject> 答:列出<MyCustomObject>
B. List<MyCustomObject> B.列出<MyCustomObject>

MyCustomObject has various fields. MyCustomObject有各种字段。 For instance a field id 例如,字段ID

In my program, I need to check if same id exists in both lists. 在我的程序中,我需要检查两个列表中是否存在相同的id 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 (例如HashMap)而不是使用列表 - 假设您的id是int,它可能看起来像:

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. 注意:假设id是唯一的。

A linear-time algorithm is to hash the ID values in the first list against a Boolean. 线性时间算法是将第一个列表中的ID值与布尔值进行散列。 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. 然后,您在第二个列表上行进以查找ID值,如果散列已包含该ID的密钥,则在两个列表之间共享该ID。

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. 您还可以通过按ID排序列表来改进O(n ^ 2)的运行时间,这是一个O(n log n)操作,并且线性地遍历列表以查看是否共享任何值。 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. 但是,我不知道你的要求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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