Sometimes we added large amount of data to ArrayList where some values will get added twice or thrice which may conflict. So It is better to remove them. The easiest way to remove repeated elements is to add the contents to a Set (which will not allow duplicates) and then add the Set back to the ArrayList.
Here is the code:
import java.util.*;
public class RemoveDuplicate {
public static void removeDuplicates(ArrayList list) {
HashSet set = new HashSet(list);
list.clear();
list.addAll(set);
}
public static void main(String args[]) {
ArrayList list = new ArrayList();
list.add("a");
list.add("b");
list.add("a");
list.add("c");
list.add("b");
removeDuplicates(list);
System.out.println("ArrayList : ");
for (Object data : list) {
System.out.println(data);
}
}
}
Output:
| ArrayList: b c a |
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.