Convert Array to Set (HashSet) in Java

Exercise:

Write a Java Program to convert array to set (HashSet).

Click Here to View the Solution!
import java.util.*;
public class ArrayToSet {
  
     public static void main(String[] args) {
  
         String[] array = {"Hello", "World", "!"};
         Set<String> set = new HashSet<>(Arrays.asList(array));
         System.out.println("Set: " + set);
     }
 } 
Click Here to View the Output!
Set: [!, Hello, World]
Click Here to View the Explanation!
  • In this program, for converting an array to a HashSet, we firstly created an array which is also named as array.
  • In order for the conversion to take place, we first have to transform the array into a list through asList() method since the list type is taken up by the HashSet for the constructor.
  • Finally, the elements of this newly created list are passed for initializing the set.

%d bloggers like this: