patternjavaMinor
An elegant way to find diff of two list of objects in Java
Viewed 0 times
objectswayjavatwoelegantdifffindlist
Problem
This is the simplest possible implementation.
The two lists will contain at max, 3-5 elements, so the size of lists is not a matter of concern.
Any recommendation on how can I make this pretty?
The two lists will contain at max, 3-5 elements, so the size of lists is not a matter of concern.
Any recommendation on how can I make this pretty?
private ListsHolder findDiffOfLists(List objsFromDB, List objsFromRequest) {
ListsHolder holder = this.new ListsHolder(); //An object holding two lists
for(MyObjRequest req_obj : objsFromRequest){
boolean isAdded = false;
for(MyObject db_obj : objsFromDB){
if(isSameObj(db_obj, req_obj)){
db_obj.setVal(req_obj.getVal()); //Set new value
holder.matchingObjList.add(db_obj);
isAdded = true;
break;
}
}
if(!isAdded){
holder.newObjList.add(req_obj); //If element does not exist
}
}
return holder;
}
private boolean isSameObj(MyObject db_obj, MyObjRequest req_obj) {
return req_obj.getMatch().equals(db_obj.getMatch());
}Solution
I would create this method:
and refactor accordingly.
Beyond that the only suggestion I would have is perhaps some better variable names (at least use a single naming style; if you don't already have one, use this: http://www.oracle.com/technetwork/java/codeconventions-135099.html#367).
private MyObject findMatch(List objsFromDB, MyObjRequest req_obj){
for(MyObject db_obj : objsFromDB){
if(isSameObj(db_obj, req_obj)){
return db_obj;
}
}
return null;
}and refactor accordingly.
Beyond that the only suggestion I would have is perhaps some better variable names (at least use a single naming style; if you don't already have one, use this: http://www.oracle.com/technetwork/java/codeconventions-135099.html#367).
Code Snippets
private MyObject findMatch(List<MyObject> objsFromDB, MyObjRequest req_obj){
for(MyObject db_obj : objsFromDB){
if(isSameObj(db_obj, req_obj)){
return db_obj;
}
}
return null;
}Context
StackExchange Code Review Q#11451, answer score: 2
Revisions (0)
No revisions yet.