On this java tutorial, we will be discussing on how to convert Set to Array of objects. We will be leveraging the method toArray of the Set class. On one of our articles on how to convert an array to set, we have discussed a unique property of Set class of java Collections framework that doesn’t allow duplicates on its elements.

Set to Array Conversion source code

This java source code shows how to convert a Set of strings into an array. The conversion is done by using the toArray(String[] array) method of Set class of java collections framework. This method returns an array of objects which we are trying to accomplish.

package com.javatutorialhq.tutorial;

import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/*
 * Java tutorial Example source code to convert Set to Array of Strings
 */

public class SetToArray {

	public static void main(String[] args) {
		Set set = new HashSet();
		// adding elements to our set
		set.add("Switzerland");
		set.add("Land of Java Tutorial");
		set.add("Array Example");

		// Converting our set to Array
		String[] arrayString = set.toArray(new String[set.size()]);
		for(String s: arrayString){
			// printing the contents of our array
			System.out.println(s);
		}

	}

}

Sample Output in the running the java program to convert Set to Array

Land of Java Tutorial
Array Example
Switzerland