Array to Collection Java


After knowing how to convert collection to array, let us see the other way of array to collection conversion. The client data may be available in array form (like shareholders names) and is required to convert into a DS form.

The method used is asList() method. Let us see its signature as defined in java.util.Arrays class

  • static List asList(T array): It is useful to convert an array into a List. The method returns a List object with the elements of the array and further elements cannot be added to the list.
Following example uses above method to convert array to collection class ArrayList.
import java.util.*;
public class ArrayToCollection
{
  public static void main(String args[])
  {
    String statesArray[] = { "Andhra Pradesh", "Telangana", "Tamilnadu", "Karnataka" };
    System.out.println("Array elements: " + Arrays.toString(statesArray));

    List statesList = Arrays.asList(statesArray);
    System.out.println("List elements: " + statesList);
  }
}

Array to Collection JavaOutput Screenshot on Array to Collection Java

Here only one style of using asList() is given. To know more styles of conversion of array to collection see Array to ArrayList

To know Java indepth, read Java Differences on 80 Topics

Leave a Comment

Your email address will not be published.