I have an array, say List<Integer>
139, 127, 127, 139, 130
How to remove duplicates of it and keep its order unchanged? i.e. 139, 127, 130
The first and easiest approach to remove duplicates is to sort the array using QuickSort or MergeSort in O(nlogn) time and then remove repeated elements in O(n) time. One advantage of sorting arrays is that duplicates will come together, making it easy to remove them.
When duplicates are removed, the first occurrence of the value in the list is kept, but other identical values are deleted. Because you are permanently deleting data, it's a good idea to copy the original range of cells or table to another worksheet or workbook before removing duplicate values.
Use an instance of java.util.LinkedHashSet
.
Set<Integer> set = new LinkedHashSet<>(list);
With this one-liner:
yourList = new ArrayList<Integer>(new LinkedHashSet<Integer>(yourList))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With