How do I remove repeated elements from ArrayList?

后端 未结 30 1736
难免孤独
难免孤独 2020-11-21 06:24

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

30条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-21 06:50

    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.

提交回复
热议问题