Java program to convert array to set (hashset) and vice versa
Here is a Java program to convert an array to a HashSet and a HashSet to an array:
import java.util.Arrays; import java.util.HashSet; public class ConvertArrayToSetAndSetToArray { public static void main(String[] args) { // Convert array to HashSet String[] arr = {"apple", "banana", "orange", "apple"}; HashSet<String> set = new HashSet<>(Arrays.asList(arr)); System.out.println("HashSet: " + set); // Convert HashSet to array String[] newArr = set.toArray(new String[set.size()]); System.out.println("Array: " + Arrays.toString(newArr)); } }
This program first creates an array of strings, arr
. It then converts the array to a HashSet
using the Arrays.asList()
method to create a List
from the array, and passing the List
to the HashSet
constructor. The HashSet
constructor removes any duplicate elements in the array, so the resulting HashSet
contains only unique elements.
Next, the program converts the HashSet
back to an array using the toArray()
method of the HashSet
class. The resulting array has the same elements as the original array, but the order may be different because a HashSet
does not guarantee element order.
Note that this program assumes that the array and the HashSet
contain only elements of the same type (in this case, String
). If the array or HashSet
contains elements of different types, then you will need to use a generic type (e.g., Object
) and perform type casting.