views:

700

answers:

2

Question is simple:

I have two List

List<String> columnsOld = DBUtils.GetColumns(db, TableName);
List<String> columnsNew = DBUtils.GetColumns(db, TableName);

And I need to get the intersection of these. Is there a quick way to achieve this?

+14  A: 

You can use retainAll method:

columnsOld.retainAll (columnsNew);
Roman
+3  A: 

Since retainAll won't touch the argument collection, this would be faster:

List<String> columnsOld = DBUtils.GetColumns(db, TableName); 
List<String> columnsNew = DBUtils.GetColumns(db, TableName); 

for(int i = columnsNew.size() - 1; i > -1; --i){
    String str = columnsNew.get(i);
    if(!columnsOld.remove(str))
        columnsNew.remove(str);
}

The intersection will be the values left in columnsNew. Removing already compared values fom columnsOld will reduce the number of comparisons needed.

bjornhol
But your code definitly should be extracted to a new separate method because it's absolutely unclear from this code what does it do. And I also wouln't have refused an additional unit test for this code.
Roman
Agree, good method separation, naming and unit tests is always rule number one.
bjornhol