Introduction
In Java, an Array is an index-based data structure that stores similar types of data, while a Set is a collection of unique elements. The process of converting an array to a set in Java is a common use case, especially when duplicate elements are not desired. In this lab, we will learn how to convert an array to a set in Java using various methods.
Create a Java file
Let's create a new Java file in the ~/project directory using the following command:
touch ~/project/ArrayToSet.java
Import necessary classes
In our Java file, we will first need to import the necessary classes for our program. We will be using the HashSet, Collections, Arrays, and Set classes. Add the following code to import these classes:
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
Create an array
Let's create a simple array of strings with some duplicate elements. Add the following code:
String[] fruits = {"Apple", "Orange", "Banana", "Orange"};
Convert the array to a set using addAll()
In this step, we will convert the array to a set using the addAll() method of the Collections class. The addAll() method adds all the elements of an array to the specified collection. Add the following code to the main() method:
Set<String> fruitsSet = new HashSet<>();
Collections.addAll(fruitsSet, fruits);
System.out.println(fruitsSet);
Convert the array to a set using asList()
In this step, we will convert the array to a set using the asList() method of the Arrays class. The asList() method returns a list of the array, which can be converted to a set using the Set constructor. Add the following code to the main() method:
Set<String> fruitsSet = new HashSet<>(Arrays.asList(fruits));
System.out.println(fruitsSet);
Convert the array to a set using Java 8 Streams
In this step, we will convert the array to a set using the toSet() method of the Collectors class from Java 8 Streams. The toSet() method collects the elements of a stream into a Set instance. Add the following code to the main() method:
Set<String> fruitsSet = Arrays.stream(fruits)
.collect(Collectors.toSet());
System.out.println(fruitsSet);
Compile and run the code
We can compile and run our Java program using the following command:
javac ArrayToSet.java && java ArrayToSet
In the output, we should see the unique elements of our array, which were added to the set during conversion.
Summary
In this lab, we learned how to convert an array to a set in Java using three different methods: addAll(), asList(), and Java 8 Streams toSet(). We also learned how to import the necessary classes, create an array, and run the Java program using the command line. By understanding these concepts, we can easily convert an array to a set in Java.



