How to Convert ArrayList to LinkedList in Java

In this post, we are going to convert ArrayList to LinkedList in Java. ArrayList and LinkedList both are classes and use to implement array-based list and linkedlist based list respectively.

Where ArrayList stores data in an Array-like list, LinkedList uses linkedlist data structure to store data. Both classes implement List interface in Java collection framework hierarchy.

To convert ArrayList, there are several ways, and some of them we are using here like passing ArraList as an argument to LinkedList constructor or adding ArrayList elements one by one using add() method or using stream API to get stream elements to LinkedList.

Time for an Example:

Let's take an example to convert ArrayList to LinkedList. Here we are passing ArrayList elements to the LinkedList constructor and getting a new data structure.

import java.util.ArrayList;
import java.util.LinkedList;

public class Main {
	public static void main(String[] args){
		ArrayList<String> arrList = new ArrayList<>();
		arrList.add("Mango");
		arrList.add("Apple");
		arrList.add("Orange");
		System.out.println(arrList);
		// ArrayList to LinkedList
		LinkedList<String> linkList = new LinkedList<>(arrList);
		System.out.println("Linked List:");
		System.out.println(linkList);
	}
}


[Mango, Apple, Orange]
Linked List:
[Mango, Apple, Orange]

Another Example:

Let's create another example to convert ArrayList to LinkedList. Here, we are using add() method to add elements to LinkedList.

import java.util.ArrayList;
import java.util.LinkedList;

public class Main {
	public static void main(String[] args){
		ArrayList<String> arrList = new ArrayList<>();
		arrList.add("Mango");
		arrList.add("Apple");
		arrList.add("Orange");
		System.out.println(arrList);
		// ArrayList to LinkedList
		LinkedList<String> linkList = new LinkedList<>();
		for (String arr : arrList) {
			linkList.add(arr);
		}
		System.out.println("Linked List:");
		System.out.println(linkList);
	}
}


[Mango, Apple, Orange]
Linked List:
[Mango, Apple, Orange]

Example: Java 8

If you are using Java 8 or higher version then you can get the advantage of Java Stream API to convert ArrayList to LinkedList. Here, we are using stream to collect ArrayList elements into LinkedList.

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.stream.Collectors;

public class Main {
	public static void main(String[] args){
		ArrayList<String> arrList = new ArrayList<>();
		arrList.add("Mango");
		arrList.add("Apple");
		arrList.add("Orange");
		System.out.println(arrList);
		// ArrayList to LinkedList
		LinkedList<String> linkList = arrList.stream().collect(Collectors.toCollection(LinkedList::new));
		System.out.println("Linked List:");
		System.out.println(linkList);
	}
}


[Mango, Apple, Orange]
Linked List:
[Mango, Apple, Orange]