Array to Set Java


Many a times, the client gets data in an array form and it may be required to you in a set or list form. Here we create first a list object with array elements and list is converted into set (or vice versa also of converting set to array). Let us do with Array to Set.
Following code on Array to Set does the job.
import java.util.*;
public class ArrayToSet
{
  public static void main(String args[]) 
  {
    String alphabetsArray[] = {"A","B","C","A","E","B"};
    List alphabetsList = Arrays.asList(alphabetsArray);
    Set alphabetsSet = new HashSet(alphabetsList);
					                // printing elements
    System.out.println("Array elements: " + Arrays.toString(alphabetsArray));
    System.out.println("List elements: " + alphabetsList);
    System.out.println("Set elements: " + alphabetsSet);
  }
}

Array to Set

String alphabetsArray[] = {“A”,”B”,”C”,”A”,”E”,”B”};
List alphabetsList = Arrays.asList(alphabetsArray);
Set alphabetsSet = new HashSet(alphabetsList);

A string array, alphabetsArray, is created where the elements A and B are repeated (duplicates). First, the array alphabetsArray is converted into list alphabetsList with asList() method of Arrays class. The list object alphabetsList is passed to HashSet constructor.

Observe the output screen. The order of elements is preserved in list and not in set (the output order is different from insertion order). As set stores unique elements, the repeated elements A and B are deleted.

Other similar operations:

1. Java Array to List
2. Java from List to Array
3. Java Set to Array
4. ArrayList to Array
5. Array to ArrayList
6. Char & Byte array to String
7. Confusion of reference variables and objects in arrays (array of array objects)

Leave a Comment

Your email address will not be published.