I have two Arraylists, A and B.
ArrayList A consists of classes that consist of a set of data, including an identifier called categoryID
. Multiple items in A can have the same categoryID
. CategoryID's can look like this for each item in A: [1, 1, 2, 2, 3, 4, 7]
.
ArrayList B consists of different classes that contain a different set of data, including categoryID
. categoryID
is unique for each item in this list. Example: [1, 2, 3, 4, 5, 6, 7]
.
Both lists are sorted by categoryID
, which hopefully makes this easier.
What I am trying to do is come up with a new list, C, which consists of items from listB that have at least one intersection with listA. So list C should contain the items [1, 2, 3, 4, 7]
from the given input above.
So far, my strategy is to iterate over both lists. I don't believe this is the most efficient way to do this, so I'm asking what other alternatives I can look at are.
My method:
ArrayList<classB> results = new ArrayList<classB>();
for (classA itemA : listA){
int categoryID = item.categoryID;
for (classB itemB : listB){
if (itemB.categoryID == categoryID){
if (!results.contains(itemB)){
results.add(itemB);
}
break;
}
}
}
I'm first traversing list A, grabbing the categoryID, then traversing listB to find the matching categoryID. When I find it, I check if the result list contains this item from listB. If it does not, then I add it to results and break out of the inner for loop and keep going through listA. If the result list already contains itemB, then I will simply break out of the inner for loop and keep going through listA. This method is O(n^2), which is not very nice for large data sets. Are there any ideas to improve?