snippetjavaCritical
How do I remove repeated elements from ArrayList?
Viewed 0 times
howfromrepeatedremovearraylistelements
Problem
I have an
ArrayList, and I want to remove repeated strings from it. How can I do this?Solution
If you don't want duplicates in a
Of course, this destroys the ordering of the elements in the
Collection, you should consider why you're using a Collection that allows duplicates. 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:Set set = new HashSet<>(yourList);
yourList.clear();
yourList.addAll(set);Of course, this destroys the ordering of the elements in the
ArrayList.Code Snippets
Set<String> set = new HashSet<>(yourList);
yourList.clear();
yourList.addAll(set);Context
Stack Overflow Q#203984, score: 1114
Revisions (0)
No revisions yet.