Write a Java Program to Convert Array to Set and Vice-Versa

In Java, an array is a collection of elements of the same type, while a set is an unordered collection of unique elements.

Sometimes, we need to convert an array to a set or vice versa for various reasons.

In this tutorial, we will discuss how to convert an array to a set and vice versa using Java programming language.


Convert Array to Set

To convert an array to a set in Java, we can use the Arrays.asList() method to convert the array to a List and then use the HashSet constructor to create a new set from the List.

Here’s how we can do it:

import java.util.*;

public class ArrayToSet {
    public static void main(String[] args) {
        String[] arr = {"apple", "banana", "orange", "pear", "apple"};
        List<String> list = Arrays.asList(arr);
        Set<String> set = new HashSet<String>(list);
        System.out.println(set);
    }
}

In the above example, we first create an array of String type with some duplicate elements.

Then, we convert the array to a List using the Arrays.asList() method.

Next, we create a new HashSet by passing the List as an argument to the constructor.

Finally, we print the set using the println() method.

Output:

[orange, pear, banana, apple]

As we can see from the output, the set contains only unique elements, and the order of elements is not the same as in the original array.

Convert Set to Array

To convert a set to an array in Java, we can use the toArray() method of the Set interface.

Here’s an example:

import java.util.*;

public class SetToArray {
    public static void main(String[] args) {
        Set<String> set = new HashSet<String>();
        set.add("apple");
        set.add("banana");
        set.add("orange");
        set.add("pear");
        String[] arr = set.toArray(new String[set.size()]);
        System.out.println(Arrays.toString(arr));
    }
}

In the above example, we first create a new HashSet and add some elements to it.

Then, we create a new array of String type by calling the toArray() method of the Set interface and passing the size of the set as an argument.

Finally, we print the array using the toString() method of the Arrays class.

Output:

[orange, pear, banana, apple]

As we can see from the output, the array contains the same elements as the original set, but the order of elements is not the same as in the original set.


Conclusion

In this tutorial, we have discussed how to convert an array to a set and vice versa using Java programming language.

We have used the Arrays.asList() method to convert an array to a List and the HashSet constructor to create a new set from the List.

We have also used the toArray() method of the Set interface to convert a set to an array.