从列表中删除重复元素

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.

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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)