Remove duplicates in an array without changing order of elements
Solution 1
Use an instance of java.util.LinkedHashSet
.
Set<Integer> set = new LinkedHashSet<>(list);
Solution 2
With this one-liner:
yourList = new ArrayList<Integer>(new LinkedHashSet<Integer>(yourList))
Solution 3
Without LinkedHashSet
overhead (uses HashSet
for seen elements instead which is slightly faster):
List<Integer> noDuplicates = list
.stream()
.distinct()
.collect(Collectors.toList());
Note that the order is guaranteed by the Stream.distinct() contract:
For ordered streams, the selection of distinct elements is stable (for duplicated elements, the element appearing first in the encounter order is preserved.)
Solution 4
Construct Set
from your list - "A collection that contains no duplicate elements":
Set<Integer> yourSet = new HashSet<Integer>(yourList);
And convert it back to whatever you want.
Note: If you want to preserve order, use LinkedHashSet
instead.
Related videos on Youtube
Deqing
9+ years software development working experience with C++ and C under Linux/UNIX and Windows. Knowledge in Telecom Networks and Open Source Technologies.
Updated on September 16, 2022Comments
-
Deqing over 1 year
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
-
Marco Forberg over 10 yearsdoes HashSet preserve insertion order?
-
Axel over 10 yearsYou have to use
LinkedHashSet
to preserve insertion order. -
Andreas over 10 yearsYou need a LinkedHashSet
-
Paul Vargas over 10 yearsHumm... That was a downgrade, I was using the diamond notation of Java 7 .
-
Maroun over 10 yearsSorry about that, after my coffee I'll be a totally different person.
-
user1156544 about 7 yearsThis doesn't preserve order afak