Efficient intersection of two List in Java?

后端 未结 8 599
南方客
南方客 2020-11-28 12:23

Question is simple:

I have two List

List columnsOld = DBUtils.GetColumns(db, TableName);
List columnsNew = DBUtils.GetCol         


        
8条回答
  •  天涯浪人
    2020-11-28 12:55

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

    List columnsOld = DBUtils.GetColumns(db, TableName); 
    List 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.

提交回复
热议问题