Convert the LinkedList into an Array in Java


Write a Java Program to convert the linkedlist into an array.

Click Here to View the Solution!
import java.util.LinkedList;

public class LinkedListToArray {
    public static void main(String[] args) {
        LinkedList<String> languages= new LinkedList<>();
        System.out.println("LinkedList: " + languages);
        String[] arr = new String[languages.size()];

        // Convert LinkedList into the string array
        System.out.print("Array: ");
        for(String item:arr) {
            System.out.print(item+", ");
Click Here to View the Output!
LinkedList: [Java, Python, JavaScript, CPP, Swift, HTML]
Array: Java, Python, JavaScript, CPP, Swift, HTML, 
Click Here to View the Explanation!
  • In this example, a string type linked list called languages is created firstly.
  • Elements are added to this linked list and then the list is printed on the screen.
  • Next, a string type array arr is created whose length is equal to the size of the linked list created.
  • Then languages is converted into an array using the toArray() method with arr passed as its parameter.
  • The array is then printed on the screen using the for-each loop.

%d bloggers like this: