82
36
|
I have an
ArrayList of Strings , and I want to remove repeated strings from it. How can I do this? | |||
add comment |
164
|
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 :
Of course, this destroys the ordering of the elements in the ArrayList.
| |||
show 1 more comment |
110
|
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
Then, if you need to get back a
List reference, you can use again the conversion constructor. | ||||||||||||||||||||
|
23
|
If you don't want duplicates, use a Set instead of a
List . To convert a List to a Set you can use the following code:
If really necessary you can use the same construction to convert a
Set back into a List . | ||
add comment |
11
|
There is also ImmutableSet from guava-libraries as an option:
| |||
add comment |
7
|
Here's a way that doesn't affect your list ordering:
l1 is the original list, and l2 is the list whithout repeated items (Make sure YourClass has the equals method acording to what you want to stand for equality)
| |||
add comment |
public Set
– Ondrej Bozek Jun 20 '12 at 12:06