How to get unique items from an array?

The simpliest solution without writing your own algorithm:

Integer[] numbers = {1, 1, 2, 1, 3, 4, 5};
Set<Integer> uniqKeys = new TreeSet<Integer>();
uniqKeys.addAll(Arrays.asList(numbers));
System.out.println("uniqKeys: " + uniqKeys);

Set interface guarantee uniqueness of values. TreeSet additionally sorts this values.


You can use a Set<Integer> and save lot of time since it holds unique elements. If you aren't allowed to use any class from Java Collections, sort the array and count the unique elements. You can sort the array manually or use Arrays#sort.

I'll post the Set<Integer> code:

int[] numbers = {1, 1, 2, 1, 3, 4, 5};
Set<Integer> setUniqueNumbers = new LinkedHashSet<Integer>();
for(int x : numbers) {
    setUniqueNumbers.add(x);
}
for(Integer x : setUniqueNumbers) {
    System.out.println(x);
}

Note that I prefer to use LinkedHashSet as Set implementation since it maintains the order of how the elements were inserted. This means, if your array was {2 , 1 , 2} then the output will be 2, 1 and not 1, 2.


In Java 8:

    final int[] expected = { 1, 2, 3, 4, 5 };

    final int[] numbers = { 1, 1, 2, 1, 3, 4, 5 };

    final int[] distinct = Arrays.stream(numbers)
        .distinct()
        .toArray();

    Assert.assertArrayEquals(Arrays.toString(distinct), expected, distinct);

    final int[] unorderedNumbers = { 5, 1, 2, 1, 4, 3, 5 };

    final int[] distinctOrdered = Arrays.stream(unorderedNumbers)
        .sorted()
        .distinct()
        .toArray();

    Assert.assertArrayEquals(Arrays.toString(distinctOrdered), expected, distinctOrdered);

//Running total of distinct integers found
int distinctIntegers = 0;

for (int j = 0; j < array.length; j++)
{
    //Get the next integer to check
    int thisInt = array[j];

    //Check if we've seen it before (by checking all array indexes below j)
    boolean seenThisIntBefore = false;
    for (int i = 0; i < j; i++)
    {
        if (thisInt == array[i])
        {
            seenThisIntBefore = true;
        }
    }

    //If we have not seen the integer before, increment the running total of distinct integers
    if (!seenThisIntBefore)
    {
        distinctIntegers++;
    }
}

Below code will print unique integers have a look:

printUniqueInteger(new int[]{1, 1, 2, 1, 3, 4, 5});


static void printUniqueInteger(int array[]){
    HashMap<Integer, String> map = new HashMap();

    for(int i = 0; i < array.length; i++){
        map.put(array[i], "test");
    }

    for(Integer key : map.keySet()){
        System.out.println(key);
    }
}