In Previous post we have learn how to convert Array to HashSet . In this post we will see how to convert set to array in java. We have following method for this
1. HashSet toArray() – convert to object array
toArray() method returns an array containing all of the elements in this collection. toArray() method return array of object.
import java.util.HashSet;
public class HashSetToArray {
public static void main(String[] args) {
//Constructs a new, empty set
HashSet<String> hashSet = new HashSet<String>();
//add element in it
hashSet.add("java");
hashSet.add("php");
hashSet.add("android");
//display the element
System.out.println("element in hashset ="+ hashSet);
/*
* Returns an array containing all
* of the elements in this collection
*/
Object[] array = hashSet.toArray();
//print object type array
for (Object object : array) {
System.out.println(object);
}
}
}
Output:
element in hashset =[java, android, php]
java
android
php
2. ArrayList toArray(T[] a) – convert to string array
toArray(T[]a) method convert collection to String array or with the help this method we can convert hashset to int array. For this we will create a array with size of set and then pass as argument in toArray(T []a) method , and this method return array of element of set. if you want to more information about toArray() method and how it works internally please see this post ararylist to array example . Let’s see this by code.
import java.util.HashSet;
public class HashSetToArray2 {
public static void main(String[] args) {
//Constructs a new, empty set
HashSet<String> hashSet = new HashSet<String>();
//add element in it
hashSet.add("java");
hashSet.add("php");
hashSet.add("android");
//display the element
System.out.println("element in hashset ="+ hashSet);
String [] arr = new String[hashSet.size()];
arr = hashSet.toArray(arr);
//print object type array
for (String element : arr) {
System.out.println(element);
}
}
}
Output :
element in hashset =[java, android, php]
java
android
php
3. Native method
In this method we will iterate set and add one by one all element in array.
import java.util.HashSet;
public class HashSetToArray3 {
public static void main(String[] args) {
//Constructs a new, empty set
HashSet<String> hashSet = new HashSet<String>();
//add element in it
hashSet.add("java");
hashSet.add("php");
hashSet.add("android");
//display the element
System.out.println("element in hashset ="+ hashSet);
String [] arr = new String[hashSet.size()];
int i =0;
for (String element : hashSet) {
arr[i++] = element;
}
//print array
for (String element : arr) {
System.out.println(element);
}
}
}
Output:
element in hashset =[java, android, php]
java
android
php