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

To understand this example, you should have the knowledge of the following Java programming topics:


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);
    }
}

Output

Set: [a, b, c]

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

Then, we initialize the 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 the same as Example 1.

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

We first convert the array to stream using stream() method and use collect() method with toSet() as a 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));

    }
}

Output

Array: [a, b, c]

In the above program, we have 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.

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges