从ArrayList中删除重复值 [英] Removing Duplicate Values from ArrayList

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

问题描述

我有字符串的一个ArrayList和我已经在增加了一些重复的值。我只是想删除重复值那么如何将其删除。

I have one Arraylist of String and I have added Some Duplicate Value in that. and i just wanna remove that Duplicate value So how to remove it.

下面例子我有一个想法。

Here Example I got one Idea.

List<String> list = new ArrayList<String>();
        list.add("Krishna");
        list.add("Krishna");
        list.add("Kishan");
        list.add("Krishn");
        list.add("Aryan");
        list.add("Harm");

        System.out.println("List"+list);

        for (int i = 1; i < list.size(); i++) {
            String a1 = list.get(i);
            String a2 = list.get(i-1);
            if (a1.equals(a2)) {
                list.remove(a1);
            }
        }

        System.out.println("List after short"+list);

但有任何充分的方式删除重复的表单列表。使用For循环了?
雅我可以使用的HashSet或其他方式,但只有使用数组列表做。
希望有你的这一建议。感谢您对提前你的答案。

But is there any Sufficient way remove that Duplicate form list. with out using For loop ? And ya i can do it by using HashSet or some other way but using array list only. would like to have your suggestion for that. thank you for your answer in advance.

推荐答案

您可以从列表中创建一个 LinkedHashSet 。在 LinkedHashSet 将包含每个元素只有一次,而在相同的顺序列表。然后创建一个新的列表 LinkedHashSet 。因此有效的,这是一个班轮:

You can create a LinkedHashSet from the list. The LinkedHashSet will contain each element only once, and in the same order as the List. Then create a new List from this LinkedHashSet. So effectively, it's a one-liner:

list = new ArrayList<String>(new LinkedHashSet<String>(list))

这涉及到的任何方法列表#包含列表#删除可能会减少从澳渐近运行时间( n)的(如在上面的例子),以为O(n ^ 2)。

Any approach that involves List#contains or List#remove will probably decrease the asymptotic running time from O(n) (as in the above example) to O(n^2).

修改为了在评论中提到的要求:如果你想删除重复的元素,但考虑到字符串作为的等于的忽略的话,那么你可以做类似这样的:

EDIT For the requirement mentioned in the comment: If you want to remove duplicate elements, but consider the Strings as equal ignoring the case, then you could do something like this:

Set<String> toRetain = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
toRetain.addAll(list);
Set<String> set = new LinkedHashSet<String>(list);
set.retainAll(new LinkedHashSet<String>(toRetain));
list = new ArrayList<String>(set);

有将具有的O运行时间(n * logn)时间,这仍然比许多其他的选择更好。请注意,这看起来有点多复杂得多,它可能是:我假设的为了的列表中的元素可能不会改变。如果列表中的元素的顺序并不重要,你可以简单地做

It will have a running time of O(n*logn), which is still better than many other options. Note that this looks a little bit more complicated than it might have to be: I assumed that the order of the elements in the list may not be changed. If the order of the elements in the list does not matter, you can simply do

Set<String> set = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
set.addAll(list);
list = new ArrayList<String>(set);

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

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