How to Convert LinkedList to ArrayList in java

I have already shared what is the difference between LinkedList and ArrayList in java. In this tutorial we are converting a LinkedList to ArrayList in java. We have a LinkedList of Strings in which we are storing name of the fruits. Later after conversion we are showing the elements of ArrayList to ensure that ArrayList is having the same elements that we have in LinkedList.

According to Oracle docs, we are using ArrayList constructor to convert LinkedList to ArrayList. Syntax is

new ArrayList(Collection c)

where we pass LinkedList to the Collection c and it will convert to the ArrayList.

Convert LinkedList to ArrayList Example

import java.util.*;

 class ConvertExample {
    public static void main(String args[]) {
    // Creating LinkedList Object    
    LinkedList<String> linkedlist = new LinkedList<String>();
    linkedlist.add("Mango");
    linkedlist.add("Banana"); 
    linkedlist.add("Pear");
    linkedlist.add("Apple");
    linkedlist.add("Orange");
    // Converting LinkedList to ArrayList
    List<String> list = new ArrayList<String>(linkedlist);

    for (String str : list){
      System.out.println(str);
    } 
  }
} 


Output

Mango
Banana
Pear
Apple
Orange






About The Author

Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry