How to convert Java HashSet to List/ArrayList collection
You can convert a HashSet collection to an ArrayList collection by passing the HashSet instance as an argument to the ArrayList constructor call.
Suppose you have the following HashSet instance:
public static void main(String[] args)
{
HashSet<String> animalSet = new HashSet<>();
animalSet.add("Tiger");
animalSet.add("Lion");
animalSet.add("Hyena");
}
You can convert the animalSet above by initializing an ArrayList and passing the set as an argument to the constructor call as shown below:
public static void main(String[] args)
{
HashSet<String> animalSet = new HashSet<>();
animalSet.add("Tiger");
animalSet.add("Lion");
animalSet.add("Hyena");
ArrayList<String> arrList = new ArrayList<>(animalSet);
System.out.println("arrList content: " + arrList);
// arrList content: [Lion, Hyena, Tiger]
}
And that’s how you can convert a HashSet to an ArrayList.
If you want to convert the HashSet into a List to avoid using class implementation, you can swap the arrList variable type from ArrayList to List as shown below:
public static void main(String[] args)
{
HashSet<String> animalSet = new HashSet<>();
animalSet.add("Tiger");
animalSet.add("Lion");
animalSet.add("Hyena");
List<String> list = new ArrayList<>(animalSet);
System.out.println("list content: " + list);
// list content: [Lion, Hyena, Tiger]
}
The result variable will be the same.
More Java tutorials
See allJava
How to fix Index 0 out of bounds for length 0 Java exception
Apr 28, 2023
Java
How to get the length of a 2D array in Java
Dec 19, 2022
Java
How to serialize and deserialize a binary tree in Java
Apr 6, 2022
Java
How to create a singleton class in Java
Apr 5, 2022
Java
Java abstract class - with code examples
Apr 4, 2022