Convert LinkedList to ArrayList in Java

Java 8Object Oriented ProgrammingProgramming

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);
}
raja
Published on 10-Jan-2019 08:13:16
Advertisements