Introduction
In this lab, you will learn how to convert an ArrayList to a HashSet in Java. HashSet is a collection that does not allow duplicates, so converting an ArrayList to HashSet can remove all duplicate elements from the ArrayList. You can use the add() method, HashSet constructor, or the Stream API to convert an ArrayList to HashSet.
Import Required Package
You need to import the ArrayList and HashSet packages. Add the following code to the file:
import java.util.ArrayList;
import java.util.HashSet;
Create an ArrayList
Create an ArrayList with some elements. Use the add() method to add elements to the ArrayList. Here's an example:
ArrayList<String> arrList = new ArrayList<>();
arrList.add("Mango");
arrList.add("Apple");
arrList.add("Orange");
arrList.add("Apple");
System.out.println(arrList);
Convert ArrayList to HashSet using HashSet Constructor
You can use the HashSet constructor to convert the ArrayList to a HashSet. Here's an example:
HashSet<String> hashSet = new HashSet<String>(arrList);
System.out.println("HashSet:");
System.out.println(hashSet);
Convert ArrayList to HashSet using add() Method
You can add each element of the ArrayList one by one to HashSet using the add() method to get a unique collection of elements. Here's an example:
HashSet<String> hashSet = new HashSet<String>();
for (String arr : arrList) {
hashSet.add(arr);
}
System.out.println("HashSet:");
System.out.println(hashSet);
Convert ArrayList to HashSet using Stream API
You can use Stream API if you are using Java 8 or higher version to make the conversion code more concise and compact. Here's an example:
HashSet<String> hashSet = arrList.stream().collect(Collectors.toCollection(HashSet::new));
System.out.println("HashSet:");
System.out.println(hashSet);
Save and Compile the File
After adding all the code, save the file using Ctrl+X, then press Y and Enter to confirm. To compile the file, enter the following command in the terminal:
javac ~/project/ArrayListToHashSet.java
Run the Program
After compiling the program, run the program by entering the following command in the terminal:
java ArrayListToHashSet
Summary
In this lab, you learned how to convert ArrayList to HashSet in Java using the HashSet constructor, add() method, and Stream API. By applying these techniques, you can easily get a unique collection of elements from an ArrayList.



