In Java, a set contains a collection of unique elements while an array can have duplicates. While working with arrays, developers often encounter a situation where they need to convert the given array into a set. This can be because of various reasons, such as to remove duplicates, find unique elements in an array, perform various set operations, etc. For this purpose, they can use different built-in Java methods.
This article illustrates a detailed guide on the array to a set conversion using several methods.
How to Convert an Array to a Set Using Naive Approach (Brute Force)
Brute force is one of the most convenient approaches to convert an array to a set. For this, create an empty set and add all the array elements to that set one by one.
Example: Array To Set Conversion Using Brute Force
Let’s first import the required classes (like Arrays, List, Set, etc.) from the “java.util” package:
import java.util.*;
Now, create a user-defined method at the class level and name it “arrayToSetConverter()”. Create an empty set inside the function and name it “convertedSet”. Use an enhanced for loop to iterate over the provided array and use the add() method within the loop’s body to add the element of the input array to the convertedSet:
public static <T> Set<T> arrayToSetConverter(T inputArray[])
{
Set<T> convertedSet = new HashSet<>();
for (T i : inputArray) {
convertedSet.add(i);
}
return convertedSet;
}
In the main() method, initialize an array that you want to convert, and print it on the console:
Public static void main(String args[])
{String[] authors = {"Joseph", "Mike", "Chris", "Ambrose"};System.out.println("Given Array: " + Arrays.toString(authors));
Invoke the custom-defined “arrayToSetConverter()” function to perform the array-to-set conversion:
Set<String> convertedSet = arrayToSetConverter(array);
System.out.println("Converted Set: " + convertedSet); }
}
Output
How to Convert an Array to a Set Using asList() Method
In Java, the “Arrays.asList()” converts the given array into a List. You can use this method with the Set constructor, such as HashSet, to convert the List into a Set.
Example: Array To Set Conversion Using Arrays.asList()
In the main() method, initialize a String-type array and apply the Arrays.asList() method on it to convert it into a set:
String[] authors = {"Joseph", "Mike", "Chris", "Ambrose"};Set<String> convertedSet = new HashSet<String>(Arrays.asList(authors));
Finally, print the original array and the converted set on the console using the println() method:
System.out.println("Given Array: " + Arrays.toString(authors));System.out.println("The Converted Set: "+ convertedSet);
Output
How to Convert an Array to a Set Using Collections.addAll()
The addAll() method of the Collections class adds all the specified elements to the selected collection. You can specify the elements to be added either separately/individually or as an array. This method allows converting the given array into a set.
Example: Array To Set Conversion Using Collections.addAll()
First, import the required packages, and then initialize a string-type array and a set in the main() metohd:
String[] authors = {"Joseph", "Mike", "Chris", "Ambrose"};
Set<String> convertedSet = new HashSet<String>();
Use the Collections.addAll() method to add the array elements into a set:
Collections.addAll(convertedSet, authors);
Finally, display the input array and converted set on the console:
System.out.println("Given Array: " + Arrays.toString(authors));
System.out.println("The Converted Set: "+ convertedSet);
Output
How to Convert an Array to a Set Using Stream API
Stream API is a feature of the Collections API in Java 8. Users can employ the Arrays.stream() method of the Stream API along with the collect() method to convert the input array into a set.
Example: Array To Set Conversion Using Stream API
Initialize an array that you want to convert to a set and print it on the console:
String[] empNames = {"Joseph", "Mike", "Chris", "Ambrose"};System.out.println("Given Array: " + Arrays.toString(empNames));
Let’s convert the array to stream and stream to set using the “stream()” and the “Collectors.toSet()” methods, respectively. Wrap the “Collectors.toSet()” within the collect() method to collect the converted set. Store the collected set in the “convertedSet” variable:
Set<String> convertedSet = Arrays.stream(empNames).collect(Collectors.toSet());
Print the converted set on the console:
System.out.println("Converted Set: " + convertedSet);
Output
How to Convert an Array to a Set Using Set.of()
The Set.of() is a static factory method that creates an immutable Set. Users can use this method for an array to set conversion.
Example: Array To Set Conversion Using Set.of()
Initialize an array and pass it to the “Set.of()” method to convert it into a set:
String[] authors = {"Joseph", "Mike", "Chris", "Ambrose"};
Set<String> convertedSet = Set.of(authors);
Use the println() to display the original array and the converted set:
System.out.println("Given Array: " + Arrays.toString(authors));
System.out.println("The Converted Set: "+ convertedSet);
Output
How to Convert an Array to a Set Using Google Guava Library
The Google Guava library offers a Sets.newHashSet() method that can convert any given array into a set.
Example: Array To Set Conversion Using Guava Library
To use Guava Library, first, download its jar file from the official site, and add it to your Java project. Then right-click on the jar file to select “Build Path” and finally click the “Add to Build Path” option:
Now import the following packages into your program to perform an array to a set conversion:
import com.google.common.collect.Sets; import java.util.*;
After this, initialize an array that you want to convert and print all of its elements on the console:
String[] authors = {"Joseph", "Mike", "Chris", "Ambrose"};
System.out.println("Given Array: " + Arrays.toString(authors));
Let’s use the “Sets.newHashSet()” and pass the given array as a parameter to it. Print the converted set on the console using println():
Set<String> convertedSet = Sets.newHashSet(authors);
System.out.println("The Converted Set: "+ convertedSet);
Output
That’s all about converting an array to a set in Java.
How to Convert a Set to an Array in Java
Java users can convert an array to a set via methods like “copyOf()”, “toArray()”, “arraycopy()”, “Java 8 Streams”, or using the Google Guava library.
Example: Set To Array Conversion Using System.arraycopy()
The following code utilizes the System.arraycopy() method to convert the given set into an Array in Java:
package exp;
import java.util.*;
public class ArrayToSet {
public static void main(String[] args) {
Set<String> authors = new HashSet<String>();
authors.add("Mike");
authors.add("Alex");
authors.add("Joseph");
authors.add("John");
authors.add("Alexa");
System.out.println("Given Set: " + authors);
int setSize = authors.size();
String convertedArray[] = new String[setSize];
//copying elements of the set to array (from 0th index to setSize)
System.arraycopy(authors.toArray(), 0, convertedArray, 0, setSize);
System.out.println("Converted Array: " + Arrays.toString(convertedArray));
}
}
The “System.arraycopy()” in the above code accepts five parameters. The source set, the starting index of the set, the destination array, the initial index of the array, and the size of the given set. Consequently, it copies the elements of the given set to the destination array(from 0th index to setSize).
Output
This way, users can convert a set back to an array.
Conclusion
Converting an array to a set is a commonly performed task in Java. Developers do this for various purposes such as eliminating duplicate elements, performing set operations, finding unique elements, etc. Users can convert an array to a set using different methods like “Arrays.asList()”, “Collections.addAll()”, “Set.of()” and Java 8 Stream API. You can also use the Sets.newHashSet() method of the Google Guava library for arrays to set conversion. This guide has extensively illustrated different methods to perform array-to-set conversion and vice versa.