Convert Hashset To Array In Java

In this tutorial we will see how to convert HashSet to array in java. We will use two approaches convert hashset to array in this example . First we will use hashset toArray() method , Second we will iterate HashSet element and add them to array. Let’s discuss these method in details .

Program to Convert HashSet to Array in Java

Now we will see java program for hashset to array using above approaches .

1. HashSet to array Using toArray() Method

In this approach we will convert HashSet to array using hashset toArray() method . This is easiest approach . HashSet toarray() method returns an array containing all of the elements in this collection. We we will create HashSet and add element into it using add() method . Then we will use set.toArray() method on HashSet and it returns array of elements of HashSet .

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. Convert HashSet to array – Iterate HashSet

In this Approach we will iterate HashSet element and add them to array one by one as per given below java program.

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

In this tutorial we have learned about how to convert HashSet to array in java . We have used two approaches in this example .

A Guide to HashSet                                                                                                            Java Doc -HashSet

Leave a Reply

Your email address will not be published. Required fields are marked *

+ 56 = 65