Java Collection How to - Remove the duplicate in an array and sorting a string array








Question

We would like to know how to remove the duplicate in an array and sorting a string array.

Answer

import java.util.Arrays;
import java.util.Set;
import java.util.TreeSet;
/*  w w  w.  j  av a 2s. c  om*/
public class Main {
  public static void main(String[] args) {
    String[] s = {"a", "y", "x","a","d", "y","m","a","bc"};
    System.out.println(Arrays.toString(s));
    System.out.println(Arrays.toString(clean(s)));
  }

  public static String[] clean(String[] input) {
    Set<String> unique = new TreeSet<>(Arrays.asList(input));
    return unique.toArray(new String[unique.size()]);
  }
}

The code above generates the following result.