I have developed a array list something like this
ArrayList<String> list = new ArrayList<String>();
list.add("1");
list.add("8");
list.add("8");
list.add("3");
list.add("4");
Now my question is: if I want to remove the “8”s from the list, which way is better?
first way:
for(int i = 0; i < list.size(); i++) {
if(list.get(i).equals("8")) {
list.remove(i);
i--;
}
}
second way:
Iterator<String> iterator = list.iterator();
while(iterator.hasNext())
if(iterator.next().equals("8"))
iterator.remove();
Now please advise which one of them is more efficient and faster from performance point of view and also is there any other way that is something like built in function by using it we can remove duplicate without iterating that much.
Performance wise they should be similar. Have you tested?
If you want to use the built in methods, you can do this with a similar performance.(to be confirmed by testing):
Finally if you want a list without duplicates, use a Set as others have mentioned.