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:
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:
set.toArray()
use LinkedHashSet if you want to maintain the order or TreeSet if you want to have it sorted.
(Repost of: https://stackoverflow.com/a/39731584/1520422)
Using the Stream API of Java 8 this is a solution with a generic Array type:
public static <T> T[] makeUnique(T... values)
{
return Arrays.stream(values).distinct().toArray(new IntFunction<T[]>()
{
@Override
public T[] apply(int length)
{
return (T[]) Array.newInstance(values.getClass().getComponentType(), length);
}
});
}
It works for any Object type array, but not for primitive arrays.
For primitive arrays it looks like this:
public static int[] makeUnique(int... values)
{
return Arrays.stream(values).distinct().toArray();
}
And finally here is a little unit test:
@Test
public void testMakeUnique()
{
assertArrayEquals(new String[] { "a", "b", "c" }, makeUnique("a", "b", "c", "b", "a"));
assertArrayEquals(new Object[] { "a", "b", "c" }, makeUnique(new Object[] { "a", "b", "c", "b", "a" }));
assertArrayEquals(new Integer[] { 1, 2, 3, 4, 5 }, makeUnique(new Integer[] { 1, 2, 2, 3, 3, 3, 1, 4, 5, 5, 5, 1 }));
assertArrayEquals(new int[] { 1, 2, 3, 4, 5 }, makeUnique(new int[] { 1, 2, 2, 3, 3, 3, 1, 4, 5, 5, 5, 1 }));
}
Two options
Keep a map of count and element and finally only use those elements with count 1. (Need extra storage but is faster)
Sort the array and as you move through the array only use non-repeated ones.
Doesn't need extra space but will be O(n lg(n))
Here are 2 ideas:
Add all items to a Set, or create one with the constructor that has an array as a parameter (HashSet
or TreeSet
, depending on what time complexity you want). Then, for each element in the set, remove it, adding it to the next open position of a new array that is the size of the set.
Sort the array. Add the object at index 0 to an ArrayList
. Start at index 1 and go to index length - 1
. If the current element is not equal to the element at the previous index, add it to the ArrayList
. Change the ArrayList
into an array, if necessary.
Supposing an array of Objects:
Object[] arr;
{...omissis...}
List<Object> list = new ArrayList<Object>();
for(Object val: arr) {
if(!list.contains(val)) {
list.add(val);
}
}
list.toArray(new Object[0]);
Replace Object
with your Array Class if needed.