Conversion of HashSet to Arrays

In this article, we will discuss how to convert HashSet into Arrays using Collection’s toArray() method

 

Conversion of HashSet into Arrays using toArrays() method :

Method signature:

public Object toArrays();
  • Invoking toArrays() method on Set instance –> converts Set into Arrays

ConvertHashSetIntoArrays.java

package in.bench.resources.java.collections;

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

public class ConvertHashSetIntoArrays {

	public static void main(String[] args) {

		// creating HashSet object of type String
		HashSet<String> onlineMart = new HashSet<String>();

		// adding elements to HashSet object
		onlineMart.add("Flipkart");
		onlineMart.add("eBay");  
		onlineMart.add("Snapdeal");  
		onlineMart.add("Myntra");
		onlineMart.add("Amazon");
		onlineMart.add("Shop Clues");
		onlineMart.add("Jabong");

		// creating String Arrays using HashSet size
		// conversion of HashSet to String Arrays
		String[] onlineShop = onlineMart
				.toArray(new String[onlineMart.size()]);

		System.out.println("Conversion of HashSet<String> "
				+ "to String Arrays\n");

		// print Arrays values
		System.out.println(Arrays.toString(onlineShop));
	}
}

Output:

Conversion of HashSet<String> to String Arrays

[Flipkart, Amazon, eBay, Jabong, Snapdeal, Myntra, Shop Clues]

 

References:

 

Happy Coding !!
Happy Learning !!

Conversion of Arrays to HashSet
How to convert LinkedList to contain unique elements in ascending order