Site icon

Convert HashSet of string to Array in java (example)

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]
Exit mobile version