DEV Community

Juan Sedano
Juan Sedano

Posted on • Originally published at jsedano.dev on

3 2

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.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay