How to remove duplicates from an array in Java?

To remove duplicates from an array in Java, first sort it, then collect non-repeating items to another array.

Option 1

Sort the array, then collect non-repeating items to another array:

int[] withDuplicates = new int[]{ 134, 1, 99, 86, 1, 2, 5, 5, 1, 133, 134 };

Arrays.sort(withDuplicates);

int[] temporaryArray = new int[withDuplicates.length];
int noDuplicatesLength = 0;

for (int item : withDuplicates) {
  if (noDuplicatesLength == 0 || temporaryArray[noDuplicatesLength - 1] != item) {
    temporaryArray[noDuplicatesLength] = item;
    noDuplicatesLength++;
  }
}

int[] noDuplicates = new int[noDuplicatesLength];

System.arraycopy(temporaryArray, 0, noDuplicates, 0, noDuplicates.length);

System.out.println(Arrays.toString(noDuplicates)); // [1, 2, 5, 86, 99, 133, 134]

Option 2

Use streams:

int[] withDuplicates = new int[]{ 134, 1, 99, 86, 1, 2, 5, 5, 1, 133, 134 };
int[] noDuplicates = Arrays.stream(withDuplicates).distinct().toArray();

System.out.println(Arrays.toString(noDuplicates)); // [134, 1, 99, 86, 2, 5, 133]