Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get unique items from an array?

Tags:

java

arrays

I am Java beginner, I found a few topics regarding this theme, but none of them worked for me. I have an array like this:

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

and I would need to get this output:

1, 2, 3, 4, 5

Every item from that array just once.

But how to get it?

like image 752
user984621 Avatar asked Apr 01 '13 21:04

user984621


2 Answers

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.

like image 88
Maxim Kolesnikov Avatar answered Oct 29 '22 01:10

Maxim Kolesnikov


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.

like image 40
Luiggi Mendoza Avatar answered Oct 29 '22 01:10

Luiggi Mendoza