Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove duplicates in an array without changing order of elements

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

like image 321
Deqing Avatar asked Oct 22 '13 07:10

Deqing


People also ask

How do you remove duplicates from an array effectively?

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.

Does remove duplicates remove the first or second?

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.


2 Answers

Use an instance of java.util.LinkedHashSet.

Set<Integer> set = new LinkedHashSet<>(list);
like image 143
Paul Vargas Avatar answered Sep 19 '22 16:09

Paul Vargas


With this one-liner:

yourList = new ArrayList<Integer>(new LinkedHashSet<Integer>(yourList))
like image 45
Andrey Chaschev Avatar answered Sep 18 '22 16:09

Andrey Chaschev