top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How do I remove repeated elements from ArrayList?

+1 vote
386 views
How do I remove repeated elements from ArrayList?
posted Jun 3, 2015 by Karthick.c

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

If you don't care the ordering of the elements in the ArrayList, a clever way is to put the list into a set to remove duplication, and then to move it back to the list. Here is the code

ArrayList** list = ... // initial a list with duplicate elements
Set<Integer> set = new HashSet<Integer>(list);
list.clear();
list.addAll(set);

If you DO care about the ordering, order can be preserved by putting a list into a LinkedHashSet which is in the standard JDK.

answer Jun 5, 2015 by Shyam
...