How to Convert HashSet to an ArrayList (List) in Java with Example

I have already shared the 5 difference between HashSet and ArrayList in java with example. In this tutorial we will be learning how to convert a HashSet to ArrayList (List).
We will use the ArrayList constructor to convert the HashSet to ArrayList object. Syntax is :

new ArrayList(Collection c)

HashSet to ArrayList (List) Conversion in Java Example


import java.util.*;

 class ConvertExample {
    public static void main(String args[]) {

    // Creating HashSet Object    
    HashSet<String> hashset = new HashSet<String>();
    hashset.add("Mango");
    hashset.add("Banana");
    hashset.add("Pear");
    hashset.add("Apple");
    hashset.add("Orange");
    
    // Showing HashSet elements
    System.out.println("HashSet contains : "+ hashset);
    
    // Converting HashSet to ArrayList
    List<String> list = new ArrayList<String>(hashset);

    // Showing ArrayList elements
    System.out.println("ArrayList contains :"+list);
     
  }
}


Output

HashSet contains : [Apple, Pear, Mango, Orange, Banana]
ArrayList contains :[Apple, Pear, Mango, Orange, Banana]



About The Author

Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry