Convert HashSet of string to Array in java (example)

  • HashSet class implements the Set interface, backed by a hash table.
  • HashSet contains the unique elements.
    • HashSet does not contains any duplicate keys
    • HashSet can have only 1 null key.
  • HashSet does not maintained the order of elements or keys.
  • HashSet is UnSynchronized and not thread safe.

Given a HashSet containing Sport’s name (String), We would like to convert HashSet to Array.

Program – convert HashSet<String> to array (String[]) in java

package org.learn.collection.set.hset;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class DemoHashSetToArray {

 public static void main(String[] args) {
  Set<String> setSports = new HashSet<>();
  setSports.add("Tennis");
  setSports.add("Cricket");
  setSports.add(null);
  setSports.add("Basketball");
  setSports.add(null);
  setSports.add("Golf");
  setSports.add("Boxer");  
  
  System.out.println("Set: "+ setSports);
  String[] hashSetToArray = new String[setSports.size()];
  setSports.toArray(hashSetToArray);
  
  System.out.println("Array:"+ Arrays.toString(hashSetToArray));
 }
}

Output – convert HashSet<String> to array (String[])

Set: [null, Tennis, Cricket, Golf, Basketball, Boxer]
Array:[null, Tennis, Cricket, Golf, Basketball, Boxer]
Scroll to Top