Java program to convert an Array to Set

The Arrays class of the java.util package provides a method known as asList(). This method accepts an array as an argument and, returns a List object. To convert an array to a Set object −

  •  Create an array or read it from the user.
  •  Using the asList() method of the Arrays class convert the array to a list object.
  •  Pass this list to the constructor of the HashSet object.
  •  Print the contents of the Set object.


import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class ArrayToSet {
   public static void main(String args[]){
      Scanner sc = new Scanner(;
      System.out.println("Enter the size of the array to be created ::");
      int size = sc.nextInt();
      String [] myArray = new String[size];

      for(int i=0; i<myArray.length; i++){
         System.out.println("Enter the element "+(i+1)+" (String) :: ");

      Set<String> set = new HashSet<>(Arrays.asList(myArray));
      System.out.println("Given array is converted to a Set");
      System.out.println("Contents of set ::"+set);


Enter the size of the array to be created ::
Enter the element 1 (String) ::
Enter the element 2 (String) ::
Enter the element 3 (String) ::
Enter the element 4 (String) ::
Given array is converted to a Set
Contents of set ::[Robert, Rahim, Rajeev, Ram]
karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know