How to convert HashSet to ArrayList in Java

Since all object collections that implement the java.util.Collection have a constructor that allows you to add another collection of a different type, you can do this kind of conversion easily.

In this example, we are creating a HashSet and adding items of type String, then we create an ArrayList with HashSet as an argument in its constructor. at the end, we go through the list to print the result.

import java.util.HashSet; 
import java.util.List;
import java.util.ArrayList;
public class ToArrayList{
public static void main(String[] args) {
// Create a HashSet
HashSet hset = new HashSet();

//add elements to HashSet
hset.add("java");
hset.add("C");
hset.add("C++");
hset.add("Objective C");
hset.add("HTML/CSS");

// print the HashSet
System.out.println("HashSet: "+ hset);

// Create an ArrayList of generic type String
//and pass hashset as argument
ArrayList arraylist = new ArrayList(hset);

// print ArrayList
System.out.println("ArrayList: "+ arraylist);
}
}
Output:

HashSet: [HTML/CSS, C, java, Objective C, C++]
ArrayList: [HTML/CSS, C, java, Objective C, C++]