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

Convert HashSet to a List/ArrayList

By Chaitanya Singh | Filed Under: Java.util package

In this tutorial we will be learning how to convert a HashSet to a List (ArrayList).

Program

Here we have a HashSet of String elements and we are creating an ArrayList of Strings by copying all the elements of HashSet to ArrayList. Following is the complete code:

import java.util.HashSet;
import java.util.List;
import java.util.ArrayList;
class ConvertHashSetToArrayList{ 
  public static void main(String[] args) {
     // Create a HashSet
     HashSet<String> hset = new HashSet<String>();
 
     //add elements to HashSet
     hset.add("Steve");
     hset.add("Matt");
     hset.add("Govinda");
     hset.add("John");
     hset.add("Tommy");
 
     // Displaying HashSet elements
     System.out.println("HashSet contains: "+ hset);
 
     // Creating a List of HashSet elements
     List<String> list = new ArrayList<String>(hset);
 
     // Displaying ArrayList elements
     System.out.println("ArrayList contains: "+ list);
  }
}

Output:

HashSet contains: [Tommy, Matt, Steve, Govinda, John]
ArrayList contains: [Tommy, Matt, Steve, Govinda, John]

Enjoyed this post? Try these related posts

  1. Java – How to Sort a HashSet?
  2. Java – Get the index of last occurrence of an element in LinkedList
  3. Iterate a LinkedList in reverse sequential order – java
  4. How to Iterate over a Set/HashSet
  5. Clone a generic LinkedList in Java
  6. Adding an element to LinkedList using add(E e) method – Java

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