DEV Community

Juan Sedano
Juan Sedano

Posted on • Originally published at jsedano.dev on

Remove duplicates in unordered array with Java using streams

Heres how to remove duplicates from an unordered primitive int array on Java using streams.

You can find the complete code for this here: remove_dupes_unordered_the_smart_way.jsh.

Consider the following straight forward problem, you receive a primitive int array and you need to return a new array only containing the unique elements.

Because we are using streams since 2014 and we know that a Set does not accept duplicates, we only need to collect the array into a set and back into an array.

int[] removeDupes(int arr[]) {
    return Arrays.stream(arr)
        .boxed()
        .collect(Collectors.toSet()).stream()
        .mapToInt(Integer::intValue).toArray();
}
Enter fullscreen mode Exit fullscreen mode

The boxed method just returns an Integer stream instead of a primitive one.

Download the complete code from this post here: remove_dupes_unordered_the_smart_way.jsh.

Top comments (1)

Collapse
 
wldomiciano profile image
Wellington Domiciano

This nice!

There is another even simpler way using distinct():

int[] removeDupesWithDistinct(int[] arr) {
  return Arrays.stream(arr).distinct().toArray();
}
Enter fullscreen mode Exit fullscreen mode