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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With