我已经开发了一个数组列表.
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.
这篇关于从列表中删除重复元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
Java从数组中删除重复项?Java Remove Duplicates from an Array?(Java从数组中删除重复项?)
如何修复调用失败来自服务器的意外响应:在 AnHow to fix Invocation failed Unexpected Response from Server: Unauthorized in Android studio(如何修复调用失败来自服务器的意外响应:在
AES 加密,解密文件中有多余的垃圾字符AES encryption, got extra trash characters in decrypted file(AES 加密,解密文件中有多余的垃圾字符)
AES 错误:给定的最终块未正确填充AES Error: Given final block not properly padded(AES 错误:给定的最终块未正确填充)
在 JAVA 中使用 AES/GCM 检测不正确的密钥Detecting incorrect key using AES/GCM in JAVA(在 JAVA 中使用 AES/GCM 检测不正确的密钥)
Java 中的 AES-256-CBCAES-256-CBC in Java(Java 中的 AES-256-CBC)