Read Also: Check if ArrayList is Empty in Java
According to Oracle docs, we will use the ArrayList constructor to convert the HashSet to ArrayList object. The syntax of the ArrayList constructor is given below:
new ArrayList(Collection c)
where we pass HashSet to the Collection c and it will convert to the ArrayList.
Convert HashSet to ArrayList (List) in Java Example
In the below Java program, the HashSet object is created. Then the HashSet.add() method is used to add elements to the HashSet object. After that, an ArrayList list is created and it is initialized using the elements of the HashSet using a parameterized constructor.import java.util.*; class HashSetToArrayList { 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]
That's all for today. Please mention in the comments if you have any questions related to the how to convert HashSet to ArrayList/List in Java with example.