如何从ArrayList中删除重复的元素?

问题描述:

我有一个 ArrayList Strings ,我想删除重复的字符串。

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

如果您不想在集合,您应该考虑为什么您使用允许重复的集合。删除重复元素的最简单方法是将内容添加到 Set (这将不允许重复),然后添加 Set 回到 ArrayList

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:

List<String> al = new ArrayList<>();
// add elements to al, including duplicates
Set<String> hs = new HashSet<>();
hs.addAll(al);
al.clear();
al.addAll(hs);

当然,这破坏了 ArrayList

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