Skip to content
Related Articles

Related Articles

Improve Article
Convert an Array into Collection in Java
  • Last Updated : 26 Oct, 2020

Java Collection provides an architecture to store and manipulate the group of objects. The datatype of data can be changed to general data type like array into Collection. To convert array-based data into Collection based we can use java. util. Arrays class. This class provides a static method asList(T… a) that converts the array into Collection.

Steps:

  • Define a function to write logic
  • Take array input from the user
  • Convert array input into Collection with help of asList() function.

Methods used:

1. asList(): This method of java.util.Arrays class is used to return a fixed-size list backed by the specified array and acting as a bridge between array-based and collection-based APIs, in combination with Collection.toArray().

This runs in O(1) time.

Example 1:



Java




// Convert an Array into Collection in Java
  
// import java util library
import java.util.*;
  
// class for writing logic of the problem
public class ArrayToCollection {
    public static void main(String args[])
    {
        // array input
        String playersArray[]
            = { "Virat", "Sachin", "Rohit", "Bumrah" };
        
        // printing input elements for comparision
        System.out.println("Array input: "
                           + Arrays.toString(playersArray));
        
        // converting array into Collection
        // with asList() function
        List playersList = Arrays.asList(playersArray);
        
        // print converted elements
        System.out.println("Converted elements: "
                           + playersList);
    }
}

Output:

Array input: [Virat, Sachin, Rohit, Bumrah]
Converted elements: [Virat, Sachin, Rohit, Bumrah]

Example 2:

Java




// Convert an Array into Collection in Java
  
// import java util library
import java.util.*;
  
public class ArrayToCollection {
    
    public static void main(String args[])
    {
        String countryArray[]
            = { "India", "Pakistan", "Afganistan",
                "Srilanka" };
        
        System.out.println("Array input: "
                           + Arrays.toString(countryArray));
  
        List countryList = Arrays.asList(countryArray);
        System.out.println("Converted elements: "
                           + countryList);
    }
}

Output:

Array input: [India, Pakistan, Afganistan, Srilanka]
Converted elements: [India, Pakistan, Afganistan, Srilanka]

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :