Java Program to Convert Array to Set (HashSet) and Vice-Versa

In this program, you'll learn to convert an array to a set and vice versa in Java.

Example 1: Convert Array to Set

import java.util.*;

public class ArraySet {

    public static void main(String[] args) {

        String[] array = {"a", "b", "c"};
        Set<String> set = new HashSet<>(Arrays.asList(array));

        System.out.println("Set: " + set);

    }
}

When you run the program, the output will be:

Set: [a, b, c]

In the above program, we've an array named array. To convert array to set, we first convert it to a list using asList() as HashSet accepts list as a constructor.

Then, we initialize set with the elements of the converted list.


Example 2: Convert Array to Set using stream

import java.util.*;

public class ArraySet {

    public static void main(String[] args) {

        String[] array = {"a", "b", "c"};
        Set<String> set = new HashSet<>(Arrays.stream(array).collect(Collectors.toSet()));

        System.out.println("Set: " + set);

    }
}

The output of the program is same as Example 1.

In the above program, instead of converting array to list and then to a set, we use stream to convert to set.

We first convert the array to stream using stream() method and use collect() method with toSet() as parameter to convert the stream to a set.


Example 3: Convert Set to Array

import java.util.*;

public class SetArray {

    public static void main(String[] args) {

        Set<String> set = new HashSet<>();
        set.add("a");
        set.add("b");
        set.add("c");

        String[] array = new String[set.size()];
        set.toArray(array);

        System.out.println("Array: " + Arrays.toString(array));

    }
}

When you run the program, the output will be:

Array: [a, b, c]

In the above program, we've a HashSet named set. To convert set into an array, we first create an array of length equal to the size of the set and use toArray() method.