-3

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}
karel
  • 5,489
  • 46
  • 45
  • 50
user3231655
  • 75
  • 2
  • 11

1 Answers1

4

You can use TreeSet to do this .Add all the elements of the array to TreeSet and storing it back to the array.

Code

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");
}

Output

10  20  25  45  50  60  90
Johny
  • 2,128
  • 3
  • 20
  • 33