1

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.

1
  • 2
    add to set duplicate are removed Commented Apr 29, 2012 at 7:35

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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):

list.removeAll(Arrays.asList("8"));

Finally if you want a list without duplicates, use a Set as others have mentioned.

2 Comments

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).
list.removeAll(Collections.singleton("4")); this is also good I think
0

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().

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.