Convert HashSet to List in Java

In the last tutorial we had seen how to convert HashSet to TreeSet in java. In this post we will see how to convert HashSet to List/ArrayList in java. Here we have a HashSet of String elements and we are creating an ArrayList of Strings by copying all the elements of HashSet to ArrayList.

Program to Convert HashSet to List in Java



import java.util.*;

 public class HashSettoArrayList {
    public static void main(String args[]) {
        
    // Declaring a HashSet
    HashSet<String> hashset = new HashSet<String>();
    // Add elements to HashSet
    hashset.add("Pear");
    hashset.add("Apple");
    hashset.add("Orange");
    hashset.add("Papaya");
    hashset.add("Banana");
    //Showing HashSet elements
    System.out.println("HashSet contains :" + hashset);
    // Creating a List of HashSet elements
    List<String> list = new ArrayList<String>(hashset);
    
    //Showing TreeSet elements
    System.out.println("ArrayList contains :");
    for(String str : list){
        System.out.println(str);
    }
  }
 }


Output
HashSet contains :[Apple, Pear, Papaya, Orange, Banana]
ArrayList contains :
Apple
Pear
Papaya
Orange
Banana

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry