- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java program to convert a Set to an array
The Set object provides a method known as toArray(). This method accepts an empty array as argument, converts the current Set to an array and places in the given array. To convert a Set object to an array −
- Create a Set object.
- Add elements to it.
- Create an empty array with size of the created Set.
- Convert the Set to an array using the toArray() method, bypassing the above-created array as an argument to it.
- Print the contents of the array.
Example
import java.util.HashSet; import java.util.Set; public class SetToArray { public static void main(String args[]){ Set<String> set = new HashSet<String>(); set.add("Apple"); set.add("Orange"); set.add("Banana"); System.out.println("Contents of Set ::"+set); String[] myArray = new String[set.size()]; set.toArray(myArray); for(int i=0; i<myArray.length; i++){ System.out.println("Element at the index "+(i+1)+" is ::"+myArray[i]); } } }
Output
Contents of Set ::[Apple, Orange, Banana] Element at the index 1 is ::Apple Element at the index 2 is ::Orange Element at the index 3 is ::Banana
- Related Articles
- Java program to convert an Array to Set
- Java Program to convert a set into an Array
- Program to convert Array to Set in Java
- How to convert an Array to a Set in Java?
- Java program to convert a list to an array
- Java program to convert an array to a list
- Program to convert Stream to an Array in Java
- Write a program to convert an array to String in Java?
- How to convert an Array to a List in Java Program?
- Swift Program to Convert Array to Set
- Golang Program To Convert Array To Set
- Java Program to convert a List to a Set
- Program to convert set of Integer to Array of Integer in Java
- How to convert an array to Set and vice versa in Java?
- C++ Program to Convert Array to Set (Hashset)

Advertisements