Java program to convert an Array to Set

Java Programming Java8Object Oriented Programming

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.

Example

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.in);
      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) :: ");
         myArray[i]=sc.next();
      }

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

Output

Enter the size of the array to be created ::
4
Enter the element 1 (String) ::
Ram
Enter the element 2 (String) ::
Rahim
Enter the element 3 (String) ::
Robert
Enter the element 4 (String) ::
Rajeev
Given array is converted to a Set
Contents of set ::[Robert, Rahim, Rajeev, Ram]
raja
Published on 26-Apr-2018 12:03:23
Advertisements