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

  1. import java.util.*;
  2. public class ArraySet {
  3. public static void main(String[] args) {
  4. String[] array = {"a", "b", "c"};
  5. Set<String> set = new HashSet<>(Arrays.asList(array));
  6. System.out.println("Set: " + set);
  7. }
  8. }

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

  1. import java.util.*;
  2. public class ArraySet {
  3. public static void main(String[] args) {
  4. String[] array = {"a", "b", "c"};
  5. Set<String> set = new HashSet<>(Arrays.stream(array).collect(Collectors.toSet()));
  6. System.out.println("Set: " + set);
  7. }
  8. }

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

  1. import java.util.*;
  2. public class SetArray {
  3. public static void main(String[] args) {
  4. Set<String> set = new HashSet<>();
  5. set.add("a");
  6. set.add("b");
  7. set.add("c");
  8. String[] array = new String[set.size()];
  9. set.toArray(array);
  10. System.out.println("Array: " + Arrays.toString(array));
  11. }
  12. }

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.