I have an ArrayList
, and I want to remove repeated strings from it. How can I do this?
If you're willing to use a third-party library, you can use the method distinct()
in Eclipse Collections (formerly GS Collections).
ListIterable integers = FastList.newListWith(1, 3, 1, 2, 2, 1);
Assert.assertEquals(
FastList.newListWith(1, 3, 2),
integers.distinct());
The advantage of using distinct()
instead of converting to a Set and then back to a List is that distinct()
preserves the order of the original List, retaining the first occurrence of each element. It's implemented by using both a Set and a List.
MutableSet seenSoFar = UnifiedSet.newSet();
int size = list.size();
for (int i = 0; i < size; i++)
{
T item = list.get(i);
if (seenSoFar.add(item))
{
targetCollection.add(item);
}
}
return targetCollection;
If you cannot convert your original List into an Eclipse Collections type, you can use ListAdapter to get the same API.
MutableList distinct = ListAdapter.adapt(integers).distinct();
Note: I am a committer for Eclipse Collections.