Learn to convert hashset to arraylist in Java using arraylist constructor. Also learn to convert arraylist to hashset to remove duplicate elements.
1. Convert HashSet to ArrayList
To convert a given hashset to an arraylist, all we need is to use arraylist constructor and pass hashset as constructor argument. It will copy all elements from hashset to the newly created arraylist.
import java.util.ArrayList; import java.util.HashSet; public class ArrayListExample { public static void main(String[] args) { HashSet<String> namesSet = new HashSet<>(); namesSet.add("alex"); namesSet.add("brian"); namesSet.add("charles"); namesSet.add("david"); //Pass hashset to arraylist constructor ArrayList<String> namesList = new ArrayList<>(namesSet); //all elements from hashset are copied to arraylist System.out.println(namesList); } }
Program output.
[alex, brian, charles, david]
2. Convert ArrayList to HashSet
You might need to create a hashset from an arraylist if you want to remove deplicate elements from list, because sets do not allow duplicate items.
Similar to previous example, we can use constructor of HashSet
to convert a given ArrayList
to hashset.
import java.util.ArrayList; import java.util.HashSet; public class ArrayListExample { public static void main(String[] args) { ArrayList<String> namesList = new ArrayList<>(); namesList.add("alex"); namesList.add("brian"); namesList.add("charles"); namesList.add("david"); namesList.add("alex"); //Create hashset from list //duplicate elements will be removed HashSet<String> namesSet = new HashSet<>(namesList); System.out.println(namesSet); } }
Program output.
[alex, brian, charles, david]
Happy Learning !!
Read More:
A Guide to Java ArrayList
ArrayList Java Docs
HashSet Java Docs