I have an unsorted array. What is the best method to remove all the duplicates of an element if present and sort them?
Example:
{10,10,50,20,45,60,25,25,90}
Output:
{10,20,25,45,50,90}
I have an unsorted array. What is the best method to remove all the duplicates of an element if present and sort them?
Example:
{10,10,50,20,45,60,25,25,90}
Output:
{10,20,25,45,50,90}
You can use TreeSet
to do this .Add all the elements of the array
to TreeSet
and storing it back to the array
.
Integer[] arr = {10,10,50,20,45,60,25,25,90};
TreeSet<Integer> tree = new TreeSet<Integer>();
for(int i = 0; i< arr.length; i++) {
tree.add(arr[i]);
}
arr = new Integer[tree.size()];
tree.toArray(arr);
for(int i = 0; i< arr.length; i++) {
System.out.print(arr[i] + "\t");
}
10 20 25 45 50 60 90