从列表中删除重复的元素 [英] Removing duplicate elements from a List

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

问题描述

  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);

但是如上所示,它包含许多重复的元素。我想删除该列表中的所有重复项。为此,我想首先我需要将列表转换成一个集合。



Java是否提供将列表转换为集合的功能?有没有其他的设施可以从列表中删除重复项目?

解决方案

您可以转换为以下设置:

 设置< String> aSet = new HashSet< String>(list); 

或者您可以转换为一组,并返回到列表:

  list = new ArrayList< String>(new HashSet< String>(list)); 

然而,这两个都不太可能保留元素的顺序。为了保持顺序,您可以在迭代时使用 HashSet 作为辅助结构:

 列表与LT;字符串> list2 = new ArrayList< String>(); 
HashSet< String> lookup = new HashSet< String>();
for(String item:list){
if(lookup.add(item)){
//如果项目已经在集合
list2中,Set.add返回false。新增项目);
}
}
list = list2;

在重复的情况下,只有第一次出现在结果中。如果只想出现最后一次出现,那是一个更严峻的问题。我会通过倒转输入列表,应用上述方法,然后反转结果来处理它。


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.

Does Java provide the functionality of converting a list into a set? Are there other facilities to remove duplicates from a list?

解决方案

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));

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.

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

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