I have 2 lists with varying length. Both lists contain data which has to be matched with entries from the other list. Currently I am iterating both lists with a nested for-loop
.
List<MyClass1> list2 = myClass1dao.findUnmatchedEntries();
List<MyClass2> list1 = myClass2dao.findUnmatchedEntries();
for (MyClass2 list1entry : list1) {
for (MyClass1 list2entry : list2) {
if (list1entry.getName().equals(list2entry.getName())
&& list1entry.getID().equals(list2entry.getID())) {
//update entries
myClass2dao.update(list1entry);
myClass1dao.update(list2entry);
break;
}
}
}
I know that this takes exponentially longer the more elements each list has.
So my question is, how can this code be improved?
Note: I am on a java 7 code base so answers to java 7 are preferred, but java 8 is okay as well
O(n*m)
. For better performance compose and return maps fromfindUnmatchedEntries()
and use them in your names comparison mechanism. Usenames
as map keys and class (MyClass1 and MyClass2) objects as map values. \$\endgroup\$