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

查看:118
本文介绍了我如何删除从ArrayList中重复的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

字符串的ArrayList ,我想从中删除重复的字符串。我怎样才能做到这一点?

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

推荐答案

如果你不想在集合重复,你应该考虑为什么您使用的是集合允许重复。删除重复的元素的最简单方法是将内容添加到一套(这将不允许重复),然后添加设置回到的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中重复的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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