Compare 2 arrayLists
in
Programming Questions
•
7 months ago
Hi everyone, I just wanted to share this piece of code, and see if someone has a better approach.
I have 2 ArrayLists of ids (strings in my case) that I need to compare.
In the final application I'm doing 1 of the ids ArrayList comes from xml loaded from a server,
the other one represent some ids of particles already on the screen, so I need to know which one to add or to remove.
Hope it will help someone as I didn't find any code around this:
I have 2 ArrayLists of ids (strings in my case) that I need to compare.
In the final application I'm doing 1 of the ids ArrayList comes from xml loaded from a server,
the other one represent some ids of particles already on the screen, so I need to know which one to add or to remove.
Hope it will help someone as I didn't find any code around this:
ArrayList<String> A = new ArrayList<String>();
ArrayList<String> B = new ArrayList<String>();
void setup()
{
A.add("1");
A.add("2");
A.add("3");
A.add("4");
A.add("5");
A.add("7");
B.add("1");
B.add("2");
B.add("3");
B.add("4");
B.add("5");
findIndexes(A,B);
}
// Returns ArrayList [[TO ADD],[ TO REMOVE]]
ArrayList findIndexes( ArrayList _A, ArrayList _B )
{
ArrayList _A_ = _A;
ArrayList _B_ = _B;
ArrayList<ArrayList> output = new ArrayList<ArrayList>();
ArrayList<String> toadd = new ArrayList<String>();
ArrayList<String> toremove = new ArrayList<String>();
Boolean checkd = false;
Boolean revert = false;
int i,j;
if(_A.size()<_B.size())
{
_A_ = _B;
_B_ = _A;
revert = true;
}else{
revert = false;
}
// what changed in _A_
for(i=0;i<_A_.size();i++){
checkd = false;
for(j=0;j<_B_.size();j++){
if(_B_.get(j)==_A_.get(i))checkd = true;
}
if(!checkd){
toadd.add((String)_A_.get(i));
}
}
// what changed in _B_
for(i=0;i<_B_.size();i++){
checkd = false;
for(j=0;j<_A_.size();j++){
if(_A_.get(j)==_B_.get(i))checkd = true;
}
if(!checkd){
toremove.add((String)_B_.get(i));
}
}
if(revert){
output.add(toremove);
output.add(toadd);
}else{
output.add(toadd);
output.add(toremove);
}
println(output);
return output;
}
void draw()
{
}
1