How to convert an array to Set and vice versa in Java?

Array is a container which can hold a fix number of entities, which are of the same type. Each entity of an array is known as element and, the position of each element is indicated by an integer (starting from 0) value known as index.


import java.util.Arrays;
public class ArrayExample {
   public static void main(String args[]) {
      Number integerArray[] = new Integer[3];
      integerArray[0] = 25;
      integerArray[1] = 32;
      integerArray[2] = 56;


[25, 32, 56]

Whereas a Set object is a collection (object) stores another objects, it does not allow duplicate elements and allows at most null value.

Converting an array to Set object

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. Use this method to convert an array to Set.


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]

Set to array

The Set object provides a method known as toArray(). This method accepts an empty array as argument, converts the current Set to an array and places in the given array. Use this method to convert a Set object to an array.


import java.util.HashSet;
import java.util.Set;
public class SetToArray {
   public static void main(String args[]){
      Set<String> set = new HashSet<String>();
      System.out.println("Contents of Set ::"+set);
      String[] myArray = new String[set.size()];
      for(int i=0; i<myArray.length; i++){
         System.out.println("Element at the index "+(i+1)+" is ::"+myArray[i]);


Contents of Set ::[Apple, Orange, Banana]
Element at the index 1 is ::Apple
Element at the index 2 is ::Orange
Element at the index 3 is ::Banana

Updated on: 03-Jul-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started