Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove repeated elements from ArrayList?

I have an ArrayList<String>, and I want to remove repeated strings from it. How can I do this?

like image 317
user25778 Avatar asked Oct 15 '08 08:10

user25778


2 Answers

If you don't want duplicates in a 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<String> set = new HashSet<>(yourList); yourList.clear(); yourList.addAll(set); 

Of course, this destroys the ordering of the elements in the ArrayList.

like image 119
jonathan-stafford Avatar answered Dec 03 '22 10:12

jonathan-stafford


Although converting the ArrayList to a HashSet effectively removes duplicates, if you need to preserve insertion order, I'd rather suggest you to use this variant

// list is some List of Strings Set<String> s = new LinkedHashSet<>(list); 

Then, if you need to get back a List reference, you can use again the conversion constructor.

like image 41
abahgat Avatar answered Dec 03 '22 08:12

abahgat