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.

Leave a Comment