Removing Duplicate Values from ArrayList

后端 未结 18 1328
无人及你
无人及你 2020-11-30 03:24

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 o

18条回答
  •  感情败类
    2020-11-30 04:02

    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(new LinkedHashSet(list))
    

    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 toRetain = new TreeSet(String.CASE_INSENSITIVE_ORDER);
    toRetain.addAll(list);
    Set set = new LinkedHashSet(list);
    set.retainAll(new LinkedHashSet(toRetain));
    list = new ArrayList(set);
    

    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 set = new TreeSet(String.CASE_INSENSITIVE_ORDER);
    set.addAll(list);
    list = new ArrayList(set);
    

提交回复
热议问题