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

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

本文介绍了如何从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.

这篇关于如何从ArrayList中删除重复的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 08:16