Take the 2-minute tour ×

I have developed a array list something like this


Now my question is: if I want to remove the "8"s from the list, which way is better?

first way:

    if(list.get(i).equals("8")) {

second way:

Iterator<String> iterator = list.iterator();

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.

share|improve this question
add to set duplicate are removed –  Balaswamy Vaddeman Apr 29 '12 at 7:35
add comment

3 Answers

up vote 3 down vote accepted

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.

share|improve this answer
This will be less performant than OP's code. list.remove will start from the beginning of the list every time -- O(n^2) instead of OP's O(n). –  Marko Topolnik Apr 29 '12 at 8:05
That s a good point –  assylias Apr 29 '12 at 8:07
list.removeAll(Collections.singleton("4")); this is also good I think –  user1370546 Apr 29 '12 at 8:19
add comment

If you need to store the duplicates I suggest you to use Map<Integer,Integer> where the 1st Integer is the key and the 2nd is the number of key occurences . So when you add the key that already exists you just increment the corresponding counter. (In remove operation you doing vice - versa). When you need all the distinct values, you just use Map.keySet().

share|improve this answer
add comment

If you just need a set of numbers, then use HashSet and not a List. If you need to preserve the order by which you are putting the numbers, use LinkedHashSet. As for removal, always prefer the version with the iterator, even though in your particular case the performance may be comparable. The idiom with iterator is more widely applicable than indexing, for example if you used a LinkedList, indexing would result in disastrous performance.

share|improve this answer
add comment

Your Answer


