Java program to convert an array to a list

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 List 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.
  •  Print the contents of the List object.

Example

import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class ArrayToList {
   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();
      }
      List<String> list = Arrays.asList(myArray);
      System.out.println("Given array is converted to a list");
      System.out.println("Contents of list ::"+list);
      list.toArray(myArray);
   }
}

Output

Enter the size of the array to be created ::
4
Enter the element 1 (String) ::
Java
Enter the element 2 (String) ::
JavaFX
Enter the element 3 (String) ::
WebGL
Enter the element 4 (String) ::
JoGL
Given array is converted to a list
Contents of list ::[Java, JavaFX, WebGL, JoGL]
raja
Published on 26-Apr-2018 11:55:55
Advertisements