How to cast a list of strings to a string array?

Java 8Object Oriented ProgrammingProgramming

The java.util.ArrayList.toArray() method returns an array containing all of the elements in this list in proper sequence (from first to last element).This acts as bridge between array-based and collection-based APIs.

You can convert a list to array using this method of the List class −

Example

Live Demo

import java.util.ArrayList;
import java.util.List;

public class ListOfStringsToStringArray {
   public static void main(String args[]) {
      List<String> list = new ArrayList<String>();
      
      list.add("JavaFX");
      list.add("HBase");
      list.add("OpenCV");
      
      String[] myArray = new String[list.size()];
      
      list.toArray(myArray );
      System.out.println("Contents of the String array are :: ");

      for(int i = 0; i<myArray.length; i++) {
         System.out.println(myArray[i]);
      }
   }
}

Output

Contents of the String array are ::
JavaFX
HBase
OpenCV
raja
Published on 08-Jan-2018 12:49:40
Advertisements