beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Converting a HashSet to an Array

By Chaitanya Singh | Filed Under: Java.util package

Here is the program for converting a HashSet to an array.

Program

import java.util.HashSet;
class ConvertHashSettoArray{ 
  public static void main(String[] args) {
     // Create a HashSet
     HashSet<String> hset = new HashSet<String>();
 
     //add elements to HashSet
     hset.add("Element1");
     hset.add("Element2");
     hset.add("Element3");
     hset.add("Element4");
 
     // Displaying HashSet elements
     System.out.println("HashSet contains: "+ hset);
 
     // Creating an Array
     String[] array = new String[hset.size()];
     hset.toArray(array);
 
     // Displaying Array elements
     System.out.println("Array elements: ");
     for(String temp : array){
        System.out.println(temp);
     }
  }
}

Output:

HashSet contains: [Element1, Element2, Element3, Element4]
Array elements: 
Element1
Element2
Element3
Element4

Enjoyed this post? Try these related posts

  1. Java – Get the index of last occurrence of an element in LinkedList
  2. Java – LinkedList poll(), pollFirst() and pollLast() methods
  3. How to Iterate over a Set/HashSet
  4. Clone a generic LinkedList in Java
  5. Java – LinkedList peek(), peekFirst() and peekLast() methods
  6. Java – Get Set view of Keys from HashMap

Leave a Reply Cancel reply

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

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap