(Repost of: https://mcmap.net/q/568758/-how-to-get-unique-values-from-array)
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 }));
}