Remove duplicates in an array without changing order of elements

16,285

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.

Share:
16,285

Related videos on Youtube

Deqing
Author by

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, 2022

Comments

  • Deqing
    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
    Marco Forberg over 10 years
    does HashSet preserve insertion order?
  • Axel
    Axel over 10 years
    You have to use LinkedHashSet to preserve insertion order.
  • Andreas
    Andreas over 10 years
    You need a LinkedHashSet
  • Paul Vargas
    Paul Vargas over 10 years
    Humm... That was a downgrade, I was using the diamond notation of Java 7 .
  • Maroun
    Maroun over 10 years
    Sorry about that, after my coffee I'll be a totally different person.
  • user1156544
    user1156544 about 7 years
    This doesn't preserve order afak