Write a Java program to convert a hash set to a List/ArrayList


In the program, a HashSet named set is created and populated with some elements: "Black", "White", "Pink", "Red", "Green", and "Yellow". The program then converts the HashSet set to an ArrayList by passing set as an argument to the ArrayList constructor. The resulting ArrayList is assigned to the List variable res. Finally, the contents of the HashSet and ArrayList are printed to the console.

Source Code

import java.util.*;
public class HashSet_ArrayList
{
	public static void main(String[] args)
	{
		HashSet<String> set = new HashSet<String>();
		set.add("Black");
		set.add("White");
		set.add("Pink");
		set.add("Red");
		set.add("Green");
		set.add("Yellow");
		System.out.println("HashSet : " + set);
 
		//Convert HashSet to ArrayList
		List<String> res = new ArrayList<String>(set);
 
		System.out.println("ArrayList : "+ res);
	}
}

Output

HashSet : [Red, White, Pink, Yellow, Black, Green]
ArrayList : [Red, White, Pink, Yellow, Black, Green]

Example Programs