从列表中删除重复元素
我已经开发了一个数组列表.
I have developed an array list.
ArrayList<String> list = new ArrayList<String>();
list.add("1");
list.add("2");
list.add("3");
list.add("3");
list.add("5");
list.add("6");
list.add("7");
list.add("7");
list.add("1");
list.add("10");
list.add("2");
list.add("12");
但如上所示,它包含许多重复的元素.我想从该列表中删除所有重复项.为此,我认为首先我需要将列表转换为集合.
But as seen above it contains many duplicate elements. I want to remove all duplicates from that list. For this I think first I need to convert the list into a set.
Java 是否提供将列表转换为集合的功能?是否有其他工具可以从列表中删除重复项?
Does Java provide the functionality of converting a list into a set? Are there other facilities to remove duplicates from a list?
推荐答案
您可以通过以下方式转换为 Set:
You can convert to a Set with:
Set<String> aSet = new HashSet<String>(list);
或者您可以转换为集合并返回列表:
Or you can convert to a set and back to a list with:
list = new ArrayList<String>(new HashSet<String>(list));
然而,这两者都不太可能保持元素的顺序.为了保持顺序,您可以在迭代时使用 HashSet
作为辅助结构:
Both of these, however, are not likely to preserve the order of the elements. To preserve order, you can use a HashSet
as an auxiliary structure while iterating:
List<String> list2 = new ArrayList<String>();
HashSet<String> lookup = new HashSet<String>();
for (String item : list) {
if (lookup.add(item)) {
// Set.add returns false if item is already in the set
list2.add(item);
}
}
list = list2;
在重复的情况下,只有第一次出现在结果中.如果您只想出现最后一次出现,那将是一个更棘手的问题.我会通过反转输入列表,应用上述内容,然后反转结果来解决它.
In the case of duplicates, only the first occurrence will appear in the result. If you want only the last occurrence to appear, that's a tougher problem. I'd tackle it by reversing the input list, applying the above, and then reversing the result.
相关文章