Remove duplicates in an array without changing order of elements

With this one-liner:

yourList = new ArrayList<Integer>(new LinkedHashSet<Integer>(yourList))

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.


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.)


Use an instance of java.util.LinkedHashSet.

Set<Integer> set = new LinkedHashSet<>(list);