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