Convert LinkedList to ArrayList in Java


A LinkedList can be converted into an ArrayList by creating an ArrayList such that the parameterized constructor of the ArrayList initialises it with the elements of the LinkedList.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class Demo {
   public static void main(String[] args) {
      LinkedList<String> l = new LinkedList<String>();
      l.add("Orange");
      l.add("Apple");
      l.add("Peach");
      l.add("Guava");
      l.add("Pear");
      List<String> aList = new ArrayList<String>(l);
      System.out.println("The ArrayList elements are: ");
    for (Object i : aList) {
         System.out.println(i);
      }
   }
}

Output

The ArrayList elements are:
Orange
Apple
Peach
Guava
Pear

Now let us understand the above program.

The LinkedList l is created. Then LinkedList.add() is used to add the elements to the LinkedList. A code snippet which demonstrates this is as follows −

LinkedList<String> l = new LinkedList<String>();
l.add("Orange");
l.add("Apple");
l.add("Peach");
l.add("Guava");
l.add("Pear");

An ArrayList aList is created and it is initialised using the elements of the LinkedList using a parameterized constructor. Then the ArrayList is displayed using a for loop. A code snippet which demonstrates this is as follows −

List<String> aList = new ArrayList<String>(l);
System.out.println("The ArrayList elements are: ");
for (Object i : aList) {
   System.out.println(i);
}

Updated on: 25-Jun-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements