How to convert LinkedList to Array in Java?

JavaObject Oriented ProgrammingProgramming

The toArray() method of the LinkedList class converts the current Linked List object into an array of object type and returns it. This array contains 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.

Therefore, to convert a LinkedList to an array −

  • Instantiate the LinkedList class.

  • Populate it using the add() method.

  • Invoke the toArray() method on the above created linked list and retrieve the object array.

  • Convert each and every element of the object array to string.

Example

 Live Demo

import java.util.Arrays;
import java.util.LinkedList;
public class LinkedListToArray {
   public static void main(String[] args) {
      LinkedList <String> list = new LinkedList<String>();
      //Instantiating an ArrayList object
      list.add("JavaFX");
      list.add("Java");
      list.add("WebGL");
      list.add("OpenCV");
      list.add("OpenNLP");
      list.add("JOGL");
      list.add("Hadoop");
      list.add("HBase");
      list.add("Flume");
      list.add("Mahout");
      list.add("Impala");
      Object[] objectAarray = list.toArray();
      int length = objectAarray.length;;
      String [] stringArray = new String[length];
      for(int i =0; i < length; i++) {
         stringArray[i] = (String) objectAarray[i];
      }
      System.out.println("Contents of the array: \n"+Arrays.toString(stringArray));
   }
}

Output

Contents of the array:
[JavaFX, Java, WebGL, OpenCV, OpenNLP, JOGL, Hadoop, HBase, Flume, Mahout, Impala]

You can also get the String array directly by passing new String[0] to the toArray() method.

Example

 Live Demo

import java.util.Arrays;
import java.util.LinkedList;
public class LinkedListToArray {
   public static void main(String[] args) {
      LinkedList <String> list = new LinkedList<String>();
      //Instantiating an ArrayList object
      list.add("JavaFX");
      list.add("Java");
      list.add("WebGL");
      list.add("OpenCV");
      list.add("OpenNLP");
      list.add("JOGL");
      list.add("Hadoop");
      list.add("HBase");
      list.add("Flume");
      list.add("Mahout");
      list.add("Impala");
      String[] stringArray = list.toArray(new String[0]);
      System.out.println("Contents of the array: \n"+Arrays.toString(stringArray));
   }
}

Output

Contents of the array:
[JavaFX, Java, WebGL, OpenCV, OpenNLP, JOGL, Hadoop, HBase, Flume, Mahout, Impala]
raja
Published on 14-Oct-2019 08:49:03
Advertisements