Related Articles

Related Articles

Convert HashSet to a ArrayList in Java
  • Last Updated : 02 Dec, 2020

ArrayList class is a resizable array, present in java.util package. The difference between an array and an ArrayList in Java, is that the size of an array cannot be modified (i.e. if you want to append/add or remove element(s) to/from an array, you have to create a new array. However, elements can be added/appended or removed from an ArrayList without the need to create a new array. 

Hashset class present in java.util package is used to create a collection that uses a hash table for storing data items. HashSet stores the elements by using a hashing mechanism.HashSet contains unique elements only and alows null value. HashSet does not maintain the insertion order and the elements are inserted on the basis of their hashcode. HashSet is the best approach for search operations. 

In order to convert a HashSet to Arraylist, we need is to use ArrayList constructor and pass the HashSet instance as a constructor argument. It will copy all elements from HashSet to the newly created ArrayList.






// Java program to convert HashSet to ArrayList
import java.util.ArrayList;
import java.util.HashSet;
class GFG {
    public static void main(String[] args)
        HashSet<String> flower_set = new HashSet<>();
        // Pass hashset to arraylist constructor
        ArrayList<String> flower_array
            = new ArrayList<>(flower_set);
        // all elements from hashset are copied to arraylist
            "Elements of flower Arraylist are :");
        // using the get method of Arraylist to get the
        // element at index=0
        System.out.print("Element at index 0 is : "
                         + flower_array.get(0) + " ");



Elements of flower Arraylist are :
[marie-gold, rose, tulip, orchid]
Element at index 0 is : marie-gold 

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :