从列表中删除重复元素

Removing duplicate elements from a List(从列表中删除重复元素)
本文介绍了从列表中删除重复元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我已经开发了一个数组列表.

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.

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Reliable implementation of PBKDF2-HMAC-SHA256 for JAVA(PBKDF2-HMAC-SHA256 for JAVA 的可靠实现)
Correct way to sign and verify signature using bouncycastle(使用 bouncycastle 签名和验证签名的正确方法)
Creating RSA Public Key From String(从字符串创建 RSA 公钥)
Why java.security.NoSuchProviderException No such provider: BC?(为什么 java.security.NoSuchProviderException 没有这样的提供者:BC?)
Generating X509 Certificate using Bouncy Castle Java(使用 Bouncy Castle Java 生成 X509 证书)
How can I get a PublicKey object from EC public key bytes?(如何从 EC 公钥字节中获取 PublicKey 对象?)