如何从 ArrayList 中删除重复的元素? [英] How do I remove repeated elements from ArrayList?

查看:35
本文介绍了如何从 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 中删除重复的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆