本文介绍了如何从 ArrayList 中删除重复的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 ArrayList
,我想从中删除重复的字符串.我该怎么做?
I have an ArrayList<String>
, and I want to remove repeated strings from it. How can I do this?
推荐答案
如果您不希望 Collection
中有重复项,您应该考虑为什么要使用 Collection
允许重复的代码>.删除重复元素的最简单方法是将内容添加到 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
:
Set<String> set = new HashSet<>(yourList);
yourList.clear();
yourList.addAll(set);
当然,这破坏了ArrayList
中元素的顺序.
Of course, this destroys the ordering of the elements in the ArrayList
.
这篇关于如何从 ArrayList 中删除重复的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!