How do I remove repeated elements from ArrayList?

后端 未结 30 1610
难免孤独
难免孤独 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:40

    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 set = new HashSet<>(yourList);
    yourList.clear();
    yourList.addAll(set);
    

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

提交回复
热议问题