I have 2 arraylists of string object.
List sourceList = new ArrayList();
List destinationList = new ArrayList
private int compareLists(List<String> list1, List<String> list2){
Collections.sort(list1);
Collections.sort(list2);
int maxIteration = 0;
if(list1.size() == list2.size() || list1.size() < list2.size()){
maxIteration = list1.size();
} else {
maxIteration = list2.size();
}
for (int index = 0; index < maxIteration; index++) {
int result = list1.get(index).compareTo(list2.get(index));
if (result == 0) {
continue;
} else {
return result;
}
}
return list1.size() - list2.size();
}
As far as I understand it correctly, I think it's easiest to work with 4 lists: - Your sourceList - Your destinationList - A removedItemsList - A newlyAddedItemsList
The answer is given in @dku-rajkumar post.
ArrayList commonList = CollectionUtils.retainAll(list1,list2);
The simplest way is to iterate through source and destination lists one by one like this:
List<String> newAddedElementsList = new ArrayList<String>();
List<String> removedElementsList = new ArrayList<String>();
for(String ele : sourceList){
if(destinationList.contains(ele)){
continue;
}else{
removedElementsList.add(ele);
}
}
for(String ele : destinationList){
if(sourceList.contains(ele)){
continue;
}else{
newAddedElementsList.add(ele);
}
}
Though it might not be very efficient if your source and destination lists have many elements but surely its simpler.