Java – remove duplicate values from ArrayList
I have a string ArrayList in which I add some duplicate values I just want to delete duplicate values, so how to delete it
I have an idea for the example here
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);
But there are not enough ways to delete duplicate form lists For loop not used? You can use HashSet or other methods, but only array list I'd like your advice on this Thank you for answering in advance
Solution
You can create a linkedhashset from the list Linkedhashset will contain only one element per element and will be in the same order as the list Then create a new list from this linkedhashset So effective, it is a single line:
list = new ArrayList<String>(new LinkedHashSet<String>(list))
Any method involving list #contains or list #remove may reduce the asymptotic running time from O (n) (as shown in the above example) to o (n ^ 2)
Edit the requirements mentioned in the comment: if you want to delete duplicate elements, but treat the string as ignoring case, you can do the following:
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);
It will have o (n * logn) runtime, which is still better than many other options Note that this looks much more complicated than it might be: I assume that the order of the elements in the list may not change You can do this if the order of the elements in the list does not matter
Set<String> set = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER); set.addAll(list); list = new ArrayList<String>(set);