I have three lists, I need to move Animal object from list animalSource to list animalTarget using list animalFilterName. Only Animal with names present in the list animalFilterName, should be moved from animalSource to animalTarget, performance wise is there a better way of doing it than I am doing below. Using just sample data for now.
public class Animal {
private String name;
private String color;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
public class MoveAnimal {
/**
* @param args
*/
public static void main(String[] args) {
List<Animal> animalSource = new ArrayList<Animal>();
List<String> animalFilterName = new ArrayList<String>();
List<Animal> animalTarget = new ArrayList<Animal>();
animalFilterName.add("Name1");
animalFilterName.add("Name2");
Animal a1 = new Animal();
a1.setColor("Color1");
a1.setName("Name1");
Animal a2 = new Animal();
a2.setColor("Color2");
a2.setName("Name2");
Animal a3 = new Animal();
a3.setColor("Color1");
a3.setName("Name3");
Animal a4 = new Animal();
a4.setColor("Color1");
a4.setName("Name4");
Animal a5 = new Animal();
a5.setColor("Color5");
a5.setName("Name1");
animalSource.add(a1);
animalSource.add(a2);
animalSource.add(a3);
animalSource.add(a4);
animalSource.add(a5);
for(String s: animalFilterName) {
for(Animal a: animalSource) {
if(s.equals(a.getName())) {
animalTarget.add(a);
}
}
}
}
}
For better performance, you would want to use Sets. I’m pretty sure what you’re doing is an O(m * n) operation for m = animalSource.size() and n = animalFilterName.size(), since lookups in ArrayLists are order n (to the lists size)
Lookups, inserts, and removals in Sets are generally either amortized constant time or logarithmic time (to the size of the set) (depending on the specifics of the set implementation) so worst case, using sets would reduce this to O(m * log(n)) for the same m and n.
I think omitting line breaks in one line ifs and loops makes them look neater. It’s personal preference, you are not obliged to copy my style.
Edit: fixed time complexity
Another Edit: When you say move, do you mean add to one list and remove from the other? Or do you just mean add to one list?
Third Edit: fixed fragmented line