I have a list of IDs: List<Integer> updatedIds.
I have a master list (say, taken from the DB): List<Records> masterList.
I want to do the following:
- For each ID in
updatedIds, check if it’s inmasterList. If not, add the record to themasterList. - For each Record in
masterList, check if it’s inupdatedIds. If not, it is obsolete, so remove it frommasterList.
The straightforward code for this is as follows:
for (Integer updId : updatedIds) {
boolean hasMapping = false;
for (Record rec : masterList) {
if (rec.getId() == updId) { hasMapping = true; break; }
}
if (!hasMapping) {
//TODO add updId to masterList
}
}
for (Record rec : masterList) {
boolean isObsolete = true;
for (Integer updId : updatedIds) {
if (rec.getId() == updId) { isObsolete = false; break; }
}
if (isObsolete) {
//TODO remove rec from masterList
}
}
The first loop takes care of requirement 1, the second takes care of requirement 2. It looks very inefficient, and I think I may be using the wrong data structure for this kind of task.
Is there a more efficient way of implementing the algorithm above?
If you sort both lists (e.g. using Collections.sort), the updatedIDs in natural order and the masterList ordered by ID, you can set up a single loop to go through both of them. You could possibly retrieve the records in sorted order, if they come from a DB, and skip that step.