AnchovyLegend AnchovyLegend - 1 year ago 104
Java Question

Array of unique elements?

Given an array like the one below, I was wondering if there is an easy way to turn this array into an array with unique values only?

This is given:


Turn it into a result array like this, preserving the original order:


Answer Source

In Java 8, use IntStream to get unique elements of an array

int[] noDuplicates = IntStream.of(array).distinct().toArray();

The simplest way would be to create set from the array.

Integer[] array = ...
Set<Integer> set = new LinkedHashSet<Integer>(Arrays.asList(array ));

and then you can retrieve the array using:


use LinkedHashSet if you want to maintain the order or TreeSet if you want to have it sorted.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download