Java Collection Tutorial - Java Set.toArray(T[] a)


Set.toArray(T[] a) has the following syntax.

<T> T[] toArray(T[] a)


In the following code shows how to use Set.toArray(T[] a) method.

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/*from ww w . j ava  2  s  .  c  o m*/
public class Main {
  public static void main(String[] args) {
    // A string array with duplicate values
    String[] data = { "A", "C", "B", "D", "A", "B", "E", "D", "B", "C" };
    System.out.println("Original array         : " + Arrays.toString(data));

    List<String> list = Arrays.asList(data);
    Set<String> set = new HashSet<String>(list);

    System.out.print("Remove duplicate result: ");

    String[] result = new String[set.size()];
    for (String s : result) {
      System.out.print(s + ", ");

The code above generates the following result.