I have two lists. They contain objects of different types, but both types contain id and name, and id is what I am comparing on. List one is fetched from DB, and list two is sent from frontend.
What I need to do is loop through them and find which list item is newly added and which one was deleted.
I was able to do it, but the problem is that it look ugly.
Let's say I have a object that is called NameDTO which can have id and name. List two is filled with that type of objects.
This is how I did it:
final ArrayList<NamedDTO> added = new ArrayList<>();
final ArrayList<NamedDTO> removed = new ArrayList<>();
for(NamedDTO listTwoObject : listTwo) {
boolean contained = false;
for(SomeObject listOneObject : listOne) {
if(listTwoObject.getId().equals(listOneObject.getId()) {
contained = true;
}
}
if(!contained) {
added.add(listTwoObject);
}
}
for(SomeObject listOneObject : listOne) {
boolean contained = false;
for(NamedDTO listTwoObject : listTwo) {
if(listTwoObject.getId().equals(listOneObject.getId()) {
contained = true;
}
}
if(!contained) {
removed.add(new NamedDTO(listOneObject.getId(), listOneObject.getName()));
}
}
This works, I have tested it. Are there better solutions? I was thinking of using Sets so I can compare them, Is there a downside to that ?